Laravel Order by Relationship Column with Example

Published on Apr 13, 2020

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. ?

Comments (0)