ItSolutionStuff.com

Laravel Order By Multiple Columns Example

By Hardik Savani • April 16, 2024
Laravel

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, laravel 9, laravel 10 and laravel 11 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 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()

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

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent Order By Query Example

Read Now →

Laravel Eloquent orderByRaw() Query Example

Read Now →

How to Group By with Order By Desc in Laravel?

Read Now →

Laravel Order By Relation Column Example

Read Now →

Laravel Order By Relationship Sum Column Example

Read Now →

How to use Union Query with Laravel Eloquent?

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

Laravel Group By with Month and Year Example

Read Now →

Laravel Select with Sum Query Example

Read Now →

Laravel Eloquent Order By Random Row Example

Read Now →

Laravel Query Builder Where Exists Example

Read Now →

Laravel Join with Subquery in Query Builder Example

Read Now →

Laravel Order By with Column Value Example

Read Now →