Laravel orderBy on Eloquent relationships example
Laravel eloquent relationships provides easy way to get relationships data with main table. But sometimes you need to get relationships data with specific column orderBy.
In this article, I will show you how you can get eloquent relationships data with specific column orderBy.
For example, your Post model belongs to User model, and you want to get posts data order by updated_at
. You can get it as following:
Example:
$users = User::with(['posts' => function ($query) {
$query->orderBy('updated_at', 'asc');
}])->get();
This method can be used if you only want to get orderBy data once. However if you want to get orderBy on every query, then you can define it in relationships.
app/Models/User.php
<?php
public function posts()
{
return $this->hasMany('App\Models\Post')->orderBy('updated_at', 'desc');
}
If you liked the article, subscribe to our Facebook page.
Copyright 2023 HackTheStuff