Conditional relationships

If you notice that you use same relationship often with additional "where" or "orderBy" condition, you can create a separate relationship method.

Model:

// Model:
public function comments()
{
return $this->hasMany(Comment::class);
}
 
public function approvedComments()
{
return $this->comments()
->where('approved', 1);
}
 
public function latestApprovedComments()
{
return $this->comments()
->where('approved', 1)
->orderBy('created_at', 'desc');
}

Recent New Courses