Laravel 10 Eloquent Order By Length Query Tutorial
Hi dev,
I am going to show you an example of laravel order by length. We will look at an example of laravel order by string length. you'll learn laravel order by field length. you will learn laravel eloquent length(). Follow the below tutorial step of laravel eloquent length order by.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 versions.
If you want to get data in order by field length in Laravel. Then laravel eloquent provides orderByRaw() function to use CHAR_LENGTH() mysql function.
so, let's see the below example code:
Example 1: Laravel Order By Field Length 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")
->orderByraw('CHAR_LENGTH(title) ASC')
->get();
dd($posts);
}
}
Example 2: Laravel Order By Field Length 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")
->orderByraw('CHAR_LENGTH(title) 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