Laravel Order By with Column Value Example

By Hardik Savani April 16, 2024 Category : Laravel

Hi Developer,

In this tutorial, you will discover laravel order by with column value. I explained simply about laravel order by field value. you can understand a concept of laravel order by specific value. This post will give you a simple example of how to order by column values in laravel. So, let us dive into the details.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

There is a way to order by fields value in laravel project. we will use orderByRaw() function to order by specific value. so, let's see the example code:

Example 1: Laravel Order By with Column Value ASC

<?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("id", "title", "body", "status")

->orderByRaw(DB::raw("FIELD(status, 'Pending', 'Approved', 'Rejected')"))

->get();

dd($posts);

}

}

Example 2: Laravel Order By with Column Value DESC

<?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("id", "title", "body", "status")

->orderByRaw(DB::raw("FIELD(status, 'Pending', 'Approved', 'Rejected') DESC"))

->get();

dd($posts);

}

}

i hope it can help you...

Tags :
Shares