Posts Learn Components Snippets Categories Tags Tools About

How to Order By Multiple Columns in Laravel?

Learn how to order by multiple columns in Laravel query builder the easy way. Make use of multiple order by to get the right ordering for your records.

Created on Oct 08, 2021


To order by multiple columns in Laravel you can make use of the "orderBy()" method and chain it multiple times for all the conditions. This method accepts the "column" as the 1st parameter and the ordering direction (ASC / DESC) as the 2nd parameter.

Method 1: Laravel Eloquent orderBy Multiple Column

To define your orderBy in your model you can write it like below.

    ->orderBy('published_at', 'ASC')
    ->orderBy('post_status', 'DESC')
The query above will produce the following Raw SQL  query.
SELECT * FROM `posts` ORDER BY `published_at` ASC, `post_status` DESC

Method 2: Using Order By Raw

You can also use orderByRaw method and it will accept the raw query.
    ->orderByRaw("published_at ASC, post_status DESC");

Extra: Passing Array

You may also pass an array of ordering criteria and loop it through if you may want a complex ordering.

$myTable->orders = [
    ['column' => 'coloumn1', 'direction' => 'desc'], 
    ['column' => 'coloumn2', 'direction' => 'asc']
And to iterate the code above you can write it like the following.

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);

$results = $query->get();

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Order By Multiple Columns in Laravel?


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours