You can load the posts associated to a User
using with
, something like
$user = User::with('posts')->find($id);
But your scenario sounds specifically collecting the latest two Post
belonging to a User
. To limit your results you can also use scopes.
Something like the following on your Post
model would work:
public function scopeLatest($query, $latest = 2)
{
return $query->limit($latest);
}
Then collect these by:
// The user record.
$user = User::find($id);
// Latest 2 posts for this user.
$posts = $user->posts()->latest();
// Latest 5 posts for this user.
$posts = $user->posts()->latest(5);
However, should you with to load the latest 2 posts with the user in a single query - then you could make a new relation:
public function latestPosts()
{
return $this->hasMany(Post::class, 'post_id', 'id')
->orderBy('created_at', 'ASC')
->limit(2);
}
This would work in the following way:
// Load the user with the latest 2 posts.
$user = User::with('latestPosts')->find($userId);
// Access these using; this will be a Collection containing 2 `Post` records.
dd($user->latestPosts);
Basically with Eloquent, when you call $this->latestPosts
Eloquent will run latestPosts()
and hydrate the related records. Using with
this hydration occurs with a single query and the relations are already defined.
The difference between the method latestPosts()
and the property $latestPosts
is simple.
The method will always return a specific Relation Collection allowing you to chain additional conditions;
So: $user->latestPosts()->get()
is the same as $user->latestPosts
.