HDTuto.com

Laravel Eloquent Order by Relation Column Example



Hello Artisan,

In this quick example, let's see laravel orderby relationship column. let’s discuss about laravel order by on relation field. In this article, we will implement a laravel order by relation column. if you want to see example of laravel orderby belongsto relationship then you are a right place.

In this post, i will give some example of how to use orderBy with relationoship field in laravel application. you can easily use order by asc and desc with relation table column in laravel.

This example will help you with laravel 5, laravel 6 and laravel 7.

So, Let's see bellow examples that will helps you.

Example 1:

Now we will use with method for order by relation column in laravel.

So, let's see bellow examples.

Laravel Orderby Belongsto Relationship ASC

$posts = Post::with(['author' => function ($q){

$q->orderBy('name');

}])

->get();

Laravel Orderby Belongsto Relationship DESC

$posts = Post::with(['author' => function ($q){

$q->orderBy('name', 'DESC');

}])

->get();

Example 2:

Now we will use collection sortBy() and sortByDesc() method for order by relation column in laravel.

So, let's see bellow examples.

Laravel Orderby Relation Column using Collection ASC

$posts = Post::get()->sortBy(function($query){

return $query->auther->name;

})

->all();

Laravel Orderby Relation Column using Collection DESC

$posts = Post::get()->sortByDesc(function($query){

return $query->auther->name;

})

->all();

Example 3:

Now we will use inner join and use order by relation column in laravel.

So, let's see bellow examples.

Laravel Orderby Relation Column using Join ASC

$posts = Post::select('*')

->join('authors', 'posts.author_id', '=', 'authors.id')

->orderBy('authors.name', 'ASC')

->paginate(10);

Laravel Orderby Relation Column using Join DESC

$posts = Post::select('*')

->join('authors', 'posts.author_id', '=', 'authors.id')

->orderBy('authors.name', 'DESC')

->paginate(10);

I hope it can help you...




April 26, 2020 | Category : Laravel



Blog Search


Copyright © 2020 HDTuto.com. All rights reserved.