OrderBy on Eloquent relationships method in Laravel

Updated at 12-Jan-2022, By samar

OrderBy on Eloquent relationships method in Laravel

Through the use of the programming language, we will work together to solve the "OrderBy on Eloquent relationships method in Laravel" puzzle in this lesson.

You can directly call the orderBy() method on eloquent relationships to get the data from related tables in specific order.
  • Use orderBy method with ASC on eloquent relationship in Laravel to display content in alphabetical ascending order (From A to Z)

    //Define relationship method in user model - app\Models\User.php
    public function postsByTitle(){
        return $this->hasMany('App\Models\Post')->orderBy('title', 'ASC');
    }
    

    Calling the relationship method

    $data = App\Models\User::find(1)->postsByTitle()->get();

    Additional Note

    You can display data using foreach loop.

    foreach($data as $val){
        echo $val->title. "<br/>";
    }

    You can specify orderBy() directly on your Eloquent relationships. It will return the data in a specific order while calling the relationship method using with() in Laravel. In our case, we get the data in alphabetical ascending order (From A to Z).

Back to code snippet queries related laravel