How to Order by Multiple Columns in Laravel with Examples?

10-Apr-2023

.

Admin

How to Order by Multiple Columns in Laravel with Examples?

Hello Friends,

This tutorial will provide examples of how to order by multiple columns in laravel examples. I explained simply about laravel order by multiple columns. let’s discuss how to order by two columns in laravel. if you want to see an example of laravel order by multiple columns example then you are in the right place. Follow the below tutorial step on how to use multiple orders in laravel.

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 with "ASC" and "DESC".

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

So, let's see the simple code example:

Example 1: Using orderBy()


we will create PostController. so you can see the below code with output:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

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()

we will create PostController. so you can see the below code with output:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

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

#Laravel