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:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials