Laravel. Use scope() in models with relation

LaravelLaravel 4Eloquent

Laravel Problem Overview


I have two related models: Category and Post.

The Post model has a published scope (method scopePublished()).

When I try to get all categories with that scope:

$categories = Category::with('posts')->published()->get();

I get an error:

> Call to undefined method published()

Category:

class Category extends \Eloquent
{
    public function posts()
    {
        return $this->HasMany('Post');
    }
}

Post:

class Post extends \Eloquent
{
   public function category()
   {
       return $this->belongsTo('Category');
   }


   public function scopePublished($query)
   {
       return $query->where('published', 1);
   }

}

Laravel Solutions


Solution 1 - Laravel

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIlya VoView Question on Stackoverflow
Solution 1 - LaravelJarek TkaczykView Answer on Stackoverflow