You can add conditions to your relationships

1class User
2{
3 public function posts()
4 {
5 return $this->hasMany(Post::class);
6 }
7 
8 // with a getter
9 public function getPublishedPostsAttribute()
10 {
11 return $this->posts->filter(fn ($post) => $post->published);
12 }
13 
14 // with a relationship
15 public function publishedPosts()
16 {
17 return $this->hasMany(Post::class)->where('published', true);
18 }
19}

Tip given by @anwar_nairi

Like our articles?

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