Laravel. Use scope() in models with relation

You can do it inline:

$categories = Category::with(['posts' => function ($q) {
  $q->published();
}])->get();

You can also define a relation:

public function postsPublished()
{
   return $this->hasMany('Post')->published();
   // or this way:
   // return $this->posts()->published();
}

and then:

//all posts
$category->posts;

// published only
$category->postsPublished;

// eager loading
$categories->with('postsPublished')->get();

Leave a Comment