ItSolutionStuff.com

Laravel Eloquent Order By Length Query Example

By Hardik Savani • April 16, 2024
Laravel

Hello 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, laravel 10 and laravel 11 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);

}

}

I hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent addSelect() Method Example

Read Now →

How to Find Multiple Ids using Laravel Eloquent?

Read Now →

Laravel Eloquent doesntHave() Condition Example

Read Now →

Laravel Eloquent Group By Year with Sum Example

Read Now →

Laravel Copy Record using Eloquent Replicate Example

Read Now →

Laravel Eloquent Sum Multiple Columns Example

Read Now →

Laravel Eloquent withSum() and withCount() Example

Read Now →

Laravel Eloquent Group By Example

Read Now →

Laravel Eloquent take() and skip() Query Example

Read Now →

Laravel Eloquent Order By Query Example

Read Now →

Multiple orWhere Condition in Laravel Eloquent

Read Now →

Laravel Eloquent Order By Random Row Example

Read Now →

Laravel Eloquent Inner Join with Multiple Conditions Example

Read Now →

Laravel Eloquent Where Like Query Example Tutorial

Read Now →