Home / Snippets / How to Order By Multiple Columns in Laravel?
How to Order By Multiple Columns in Laravel? cover

How to Order By Multiple Columns in Laravel?

22.8K

2 years ago

0 comments

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

notion avatar

Ahabz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this