Laravel Eloquent Query Order By Length of Column

In this blog, we will be going to make Laravel Eloquent query order by length of the column. This will be very easy and helpful when you want to use this in your project. You can use this example with Laravel 6, 7, 8,  9, and 10 versions.

To do this we will require two functions orderByRaw() provided by laravel eloquent and CHAR_LENGTH() provided by MySQL function.


Example 1: Laravel Eloquent Order By Column Length in ASC

<?php

   

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

use App\Models\Blog;

  

class BlogController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index(Request $request)

    {

        $bog = Blog::select("id", "title")

                        ->orderByraw('CHAR_LENGTH(title) ASC')

                        ->get();

 

        dd($blog);

    }



Example 2: Laravel Eloquent Order By Column Length in DESC


 <?php

   

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

use App\Models\Blog;

  

class BlogController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index(Request $request)

    {

        $bog = Blog::select("id", "title")

                        ->orderByraw('CHAR_LENGTH(title) DESC')

                        ->get();

 

        dd($blog);

    }

I hope you understood the use of Laravel Eloquent Query Order By Length of Column, if you have any doubt comment below.