Laravel Order by Relationship Column with Example

Published on April 13, 2020 31 sec read

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

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

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