Level 70
User.php
public function contents()
{
return $this->hasMany(Content::class)->orderBy('updated_at');
}
Content.php
public function user()
{
return $this->belongsTo(User::class);
}
Now, in the controller, you can write the query like this way-
// Getting all latest contents of user ID = 1
$contents = User::with('contents')->findOrFail(1);
// Getting all latest contents of user ID = 1
$contentsInLast24Hours = User::with('contents', function ($query) {
$query->where('created_at', '>=', now()->subDay(1));
})->findOrFail(1);
1 like