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, 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent Order By Query Example
- Laravel Eloquent orderByRaw() Query Example
- How to Group By with Order By Desc in Laravel?
- Laravel Order By Relation Column Example
- Laravel Order By Relationship Sum Column Example
- How to use Union Query with Laravel Eloquent?
- Laravel Many to Many Eloquent Relationship Tutorial
- Laravel Group By with Month and Year Example
- Laravel Select with Sum Query Example
- Laravel Eloquent Order By Random Row Example
- Laravel Query Builder Where Exists Example
- Laravel Join with Subquery in Query Builder Example
- Laravel Order By with Column Value Example