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');
}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1183 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses