Order By Relation Column- Laravel Code Example

laravel order by relation column

Laravel Order By Relation Column

In this article, we will learn how to get the data in orderBy with the help of relations.

We can get the data in descending(DESC) or ascending(ASC)order of any column of the database. But in some cases, we have to get orderBy data from the column of another table, for that we create a relationship in the model and get the data.

There are many queries by which we can sort the data with relation some of them are as follows :

This example will help you how to get data oredrBy with the relation column

# Create controller

# Create model

# Create relation

#Create view file

# Routes

 

Create Controller

Example: 1 – Laravel Order By Relation Using orderBy();

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use App\Models\Customer;

    class CustomerController extends Controller

    {

        public function customers()

        {

            $customers = Customer::with('CustomerSalary')->orderBy('salary_id', 'DESC')->get();

            return view('index', compact('customers'));

        }

    }

Create Model – Customer.php

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;

    use Illuminate\Database\Eloquent\Model;

    use App\Models\CustomerSalary;

    class Customer extends Model

    {

        use HasFactory;

        // relation with customer salary

        public function CustomerSalary()

        {

            return $this->belongsTo(CustomerSalary::class, 'salary_id', 'id');

        }

    }

View file – index.blade.php

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">

        <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/dataTables.bootstrap4.min.css">

        <title>Laravel Order By Relation</title>

    </head>

    <body>

        <div class="container mt-5">

            <div class="text-center">

                <h1>Customers</h1>

            </div>

            <table id="example" class="table table-striped table-bordered" style="width:100%">

                <thead>

                    <tr>

                        <th>id</th>

                        <th>Name</th>

                        <th>email</th>

                        <th>address</th>

                        <th>city</th>

                        <th>state</th>

                        <th>salary</th>

                    </tr>

                </thead>

                <tbody>

                    @foreach($customers as $key => $customer)

                    <tr>

                        <td>{{++$key}}</td>

                        <td>{{$customer->name}}</td>

                        <td>{{$customer->email}}</td>

                        <td>{{$customer->address}}</td>

                        <td>{{$customer->city}}</td>

                        <td>{{$customer->state}}</td>

                        <td>{{$customer->CustomerSalary->salary}}</td>

                    </tr>

                    @endforeach

                </tbody>

            </table>

        </div>

    </body>

    </html>

Route – web.php

    <?php

    use Illuminate\Support\Facades\Route;

    /*

    |--------------------------------------------------------------------------

    | Web Routes

    |--------------------------------------------------------------------------

    |

    | Here is where you can register web routes for your application. These

    | routes are loaded by the RouteServiceProvider within a group which

    | contains the "web" middleware group. Now create something great!

    |

    */

    Route::get('/', function () {

        return view('index');

    });

    Route::get('/', 'CustomerController@customers')->name('index');

OutPut

laravel order by relation

Example : 2 – Laravel Order By Relation Using  orderBy();

public function customers()

    {

        $customers = Customer::with('CustomerSalary')->orderBy(

            'salary_id',

            'ASC'

        )->get();

        return view('index', compact('customers'));

    }

Example : 3 – Laravel Order By Relation Using  orderBy(); query

public function customers()

    {

        $customers = Customer::with(['CustomerSalary' => function ($query) {

            $query->orderBy('salary');

        }])->get();

        return view('index', compact('customers'));

    }

Example : 4 – Laravel Order By Relation Using sortBy();

public function customers()

    {

        $customers = Customer::get()->sortBy(function ($query){

            return $query->CustomerSalary->salary;

        })->all();

        return view('index', compact('customers'));

    }

Example : 5 –
Laravel Order By Relation Using sortByDesc();

    public function customers()

    {

        $customers = Customer::get()->sortByDesc(function ($query){

            return $query->CustomerSalary->salary;

        })->all();

        return view('index', compact('customers'));

    }
All the examples of order by relation mentioned above are mostly used in Laravel. Hope this article will be helpful for you.

Leave a Comment

Your email address will not be published. Required fields are marked *