How to sort by relation in Laravel Eloquent
This article will explain in detail how Laravel Eloquent can be sorted through relationships. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Sort by relation
A more complicated "technique". Do you want to sort forum topics by the latest posts? The latest updated topics in the forum are very common requirements at the front, right?
First, define a separate relationship for the latest posts on the topic:
Public function latestPost () {return $this- > hasOne (\ App\ Post::class)-> latest ();}
Then, in the controller, we can implement this "magic":
$users = Topic::with ('latestPost')-> get ()-> sortByDesc (' latestPost.created_at'); this is the end of the article on "how to sort through relationships in Laravel Eloquent". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.