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 relationship15 public function publishedPosts()16 {17 return $this->hasMany(Post::class)->where('published', true);18 }19}
Tip given by @anwar_nairi