Laravel Order by Relationship Column with Example

Published on April 13, 2020 31 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

In this short article, I’m going to share some order by relationships in Laravel.

orderBy

Use orderBy function to get record in ascending order:

$users = User::with(['location' => function ($q){
	$q->orderBy('name');
}])->get();

Descending order:

$users = User::with(['location' => function ($q){
	$q->orderBy('name', 'DESC');
}])->get();

sortBy

Use sortBy function to get record in ascending order:

$users = User::get()->sortBy(function($query){
	return $query->userCity->name;
});

Descending order:

$users = User::get()->sortByDesc(function($query){
	return $query->userCity->name;
});

Join

Inner join and order by relation column in ascending order:

$posts = Post::select('*')
          ->join('authors', 'posts.author_id', '=', 'authors.id')
          ->orderBy('authors.name', 'ASC')
          ->paginate(20);

Descending order:

$posts = Post::select('*')
          ->join('authors', 'posts.author_id', '=', 'authors.id')
          ->orderBy('authors.name', 'DESC')
          ->paginate(20);
The article is over. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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