Search code examples
laraveleloquentsql-order-bylaravel-eloquent-resource

how to make orderBy ignore value 0 in eloquent laravel


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');

Solution

  • 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();