138

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

}

1 Answer 1

243

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();
4
  • 10
    Incidentally, if you want to ONLY get where you have published posts: Category::whereHas('posts', function ($q) { $q->published(); })->get();
    – tptcat
    Jan 31, 2017 at 18:21
  • 3
    @tptcat yes. Also can be Category::has('postsPublished') in this case Feb 1, 2017 at 0:16
  • 2
    Clean question, clean answer!
    – Mojtaba Hn
    Oct 12, 2019 at 7:46
  • 2
    What if the query scope has a parameter? Aug 12, 2021 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.