i have three tables which i'm using to fetch categories and their related products,
Categories:
id | name | slug | parent_id
Products:
id | name | slug | price
Product_categories:
id | category_id | product_id
I have following menu items generated
Mens
| Topwear
| Jackets
| Shirts
| T-Shirts
Womens
| Topwear
| Kurtis
| T-Shirts
i'm using following url:
http://localhost:8000/top-wear
to display top level category products, but if i add subcategory with top level category
http://localhost:8000/top-wear/Jackets
i.e. jackets here then i should get only jacket but right now i'm getting all the products in that category, i.e. Jackets, Shirts, T-Shirts.
Controller Code is :
public function show($categorySlug, $subcategorySlug=null)
{
$child_categories=$this->categoryRepository->getchild_catproducts($categorySlug);
return view('site.pages.category', compact('child_categories'));
}
Model:
public function getchild_catproducts($categorySlug)
{
$productsLists= Category::with(['products', 'children', 'children.products'])->where('slug',$categorySlug)->get();
return $productsLists;
}
View:
@foreach($child_categories[0]->children as $cat_prod)
@foreach($cat_prod->products as $product)
<div class="col-6 col-md-4">
<div class="card list-item bg-white rounded overflow-hidden position-relative shadow-sm">
<span class="like-icon"><a class="active" href="#"> <i class="icofont icofont-heart"></i></a></span>
<a href="#">
<span class="badge badge-success">50% OFF</span>
@php ($product_img=$product->images['0']['full'])
<img src="" class="card-img-top" alt="..."></a>
<div class="card-body">
<h6 class="card-title mb-1"><a href=""></a></h6>
<div class="stars-rating"><i class="icofont icofont-star active"></i><i class="icofont icofont-star active"></i><i class="icofont icofont-star active"></i><i class="icofont icofont-star active"></i><i class="icofont icofont-star"></i> <span>613</span></div>
<p class="mb-0 text-dark"> <span class="text-black-50"><del> </del></span></p>
</div>
</div>
</div>
@endforeach
@endforeach
Category Model:
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
public function products()
{
return $this->belongsToMany(Product::class, 'product_categories', 'category_id', 'product_id');
}
Routes:
Route::get('/{categorySlug}/{subcategorySlug?}', 'Site\CategoryController@show')->name('category.show');
Please help to sort out my issue.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire