Hello Dev,Hi Guys,
This detailed guide will cover laravel order by length. if you want to see an example of laravel order by string length then you are in the right place. We will use laravel order by field length. I explained simply about 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()
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);
}
}
I hope it can help you...
Do you like below Tutorials ?
- Laravel 5.6 - Collection could not be converted to int
- Laravel - How to generate secure https URL from route?
- Laravel - Vue JS File Upload Example
- How to get last 7 days data in Laravel?
- Laravel Validation required if other field empty example
- Laravel Eloquent - When Case Statement in Select Query Example
- Laravel 7.x and 6.x Passing Variable to Javascript Example
- How to pass PHP variables in JavaScript or jQuery?