Laravel Order by Relationship Column with Example

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.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.