Reputation: 327
I've followed this code structure for a multi-level category system on Laravel 5:
This works fine. But I'm trying to put together a query to return posts in a category (by slug) but also the children categories underneath.
So heres what I've got at the moment:
$posts = Post::with('images')->whereHas('categories', function($q) use ($slug)
{
$q->where('slug', '=', $slug);
})->orderBy('created_at', 'DESC')->paginate(10);
This returns everything under the category that matches the slug passed through, but not the children. Any suggestions?
Thanks.
Upvotes: 2
Views: 1503
Reputation: 1519
If you have only one depth of subcategories, the following solution is what I would use.
<?php
$category = Category::where('slug',$slug)->first();
$posts = Post::with('images')->whereHas('categories', function($q) use ($category)
{
$q->where(function($q) use ($category) {
$q->where('id', $category->id)->orWhere('parent_id',$category->id);
});
})->orderBy('created_at', 'DESC')->paginate(10);
Upvotes: 2
Reputation: 1345
In your code, you only fetched the Post
s and their images
. If I understood correctly, what you want to fetch are the Post
s, their images
, the category
their in and childCategories
(this is a made up name) of that category
. You just need to add category.childCategories
in your with
method like so:
$posts = Post::with('images', 'categories.childCategories')->whereHas('categories', function($q) use ($slug)
{
$q->where('slug', '=', $slug);
})->orderBy('created_at', 'DESC')->paginate(10);
Remember to change the childCategories
name to whatever the child category relationship name in your Category
model.
Upvotes: 0