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);
}
}
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial