Laravel Order by Multiple Columns Examples

Oct 05, 2022 . Admin



Hello Friends,

In this tutorial we will go over the demonstration of laravel order by multiple columns examples. if you want to see an example of how to order by multiple columns in laravel then you are in the right place. step by step explain how to order two columns in laravel. we will help you to give examples of how to use multiple orders in laravel. follow the below step for the laravel order by multiple columns example.

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