Laravel Order By with Column Value Example
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...
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 firstOrNew Example
- Laravel Eloquent firstOrCreate Example
- Laravel Eloquent selectRaw() Query Example
- Laravel Eloquent Order By Query Example
- Laravel Eloquent orderByRaw() Query Example
- Multiple orWhere Condition in Laravel Eloquent
- How to Group By with Order By Desc in Laravel?
- Laravel Order By Relation Column Example
- Laravel Order By Relationship Sum Column Example
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial
- Laravel Eloquent Order By Random Row Example