Posts Learn Components new Snippets new Categories Tags 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

38 views

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.
<?php

Post::query()
    ->orderBy('published_at', 'ASC')
    ->orderBy('post_status', 'DESC')
    ->get();
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.
Post::query()
    ->orderByRaw("published_at ASC, post_status DESC");
    ->get();

Extra: Passing Array


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

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

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

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

$results = $query->get();

Other Reads

new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻