Laravel Order By Multiple Columns Example

Hey Guys,

Today, I would like to show you laravel order by multiple columns. step by step explain how to order by multiple columns in laravel. I explained simply about how to order by two columns in laravel. This article goes in detailed on how to use multiple order by in laravel.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

There are several ways to order by with multiple columns in laravel eloquent. i will give you two simple examples using orderBy() and orderByRaw() eloquent method to multiple column order by with “ASC” and “DESC”.

So, let’s see the simple code example:

Example 1: Using orderBy()

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$posts = Post::select("*")

->orderBy('created_at', 'ASC')

->orderBy('status', 'DESC')

->get();

dd($posts);

}

}

Example 2: Using orderByRaw()

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$posts = Post::select("*")

->orderByRaw("created_at ASC, status DESC");

->get();

dd($posts);

}

}

I hope it can help you…

2 thoughts on “Laravel Order By Multiple Columns Example”

Leave a Comment