Home > Blockchain >  how to make orderBy ignore value 0 in eloquent laravel
how to make orderBy ignore value 0 in eloquent laravel

Time:09-09

My problem is that I have my collection that has a position field and I want it to be sorted in ascending order, but the fields that have the value null or 0 by default are detected as smaller than those that have an index.

My question is how can I make orderBy ignore the value 0 or null.

$listing = Product::get();
$listing = $listing->orderBy('order','ASC');

CodePudding user response:

You could use CASE in your orderBy as a hack to "ignore" 0 (place it last).

$listing = Product::query()
    ->orderByRaw('CASE WHEN "order" = 0 THEN 0 ELSE 1 END DESC, "order" ASC')
    ->get();

You can also split it if you prefer.

$listing = Product::query()
    ->orderByRaw('CASE WHEN "order" = 0 THEN 0 ELSE 1 END DESC')
    ->orderBy('order')
    ->get();
$listing = Product::query()
    ->orderByDesc(DB::raw('CASE WHEN "order" = 0 THEN 0 ELSE 1 END'))
    ->orderBy('order')
    ->get();

CodePudding user response:

$listing = Product::orderByRaw('-order DESC')->get();

There is a minus sign before the column. Instead of asc, we are now sorting as desc, this is because we have inverted the values in #2 and so the sorting must also be inverted now to get the right results.

this working fine for me.

  • Related