order by multiple columns in Laravel

Created at 24-Sep-2021 , By samar

order by multiple columns in Laravel

In this tutorial, we will try to find the solution to "order by multiple columns in Laravel" through programming.

Sometimes you have to run multiple order by in single query to get the records as per required order. You can use multiple order by in Laravel using orderBy() method on multiple columns.
  • OrderBy method on multiple columns in laravel

    $users = App\Models\User::orderBy('created_at', 'desc')->orderBy('id', 'asc')->get();
    dd($users);
    

    This code snippet will show data in order for columns created_at by DESC and with column id by ASC. It follows the first order by at first and second order by at second priority.

     

    Demo code

    Route::get('/order-by', function(){
        $users = App\Models\User::orderBy('created_at', 'desc')->orderBy('id', 'asc')->get();
        dd($users);
    });

    Just copy/paste code in routes\web.php and visit http://localhost:8000/order-by  after running the php artisan serve in command line.

     

    Output :

    ^ Illuminate\Database\Eloquent\Collection {#1390 ▼
      #items: array:14 []
    }

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.