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:
  • 73 courses
  • 93 long-form tutorials
  • access to project repositories
  • access to private Discord

Recent New Courses