dimanche 5 avril 2020

Cannot get children category product in Laravel

I want to get child category products when i click on any link of a parent category, right now my relation is working properly for Single Category,

I have created a function for that in controller:

 public function show($categorySlug, $subcategorySlug=null)
    {   
        $category = $this->categoryRepository->findBySlug($categorySlug);
        $child_categories=$this->categoryRepository->getChildCategories($category->id);
        if($child_categories->childrenProdut->count()==0)
        {
            $category=$category;
        }
        else{
            $category=$child_categories->childrenProdut;
        }
        return view('site.pages.category', compact('category','child_categories'));
    }

Category Model :

public function children()
{
    return $this->hasMany(Category::class, 'parent_id');
}
public function childrenProdut()
{
    return $this->hasMany(Category::class, 'parent_id');
}
public function products()
{
return $this->belongsToMany(Product::class, 'product_categories', 'category_id', 'product_id');
}

View :

I',m getting Category and product Data using following statement :

 @forelse($category->products as $product)

Main Issue :

For single category, I'm getting data i.e. products of that category using the following :

public function findBySlug($slug)
{
    return Category::with('products')
        ->where('slug', $slug)
        ->where('menu', 1)
        ->first();
}

but i have manipulated the code for the children categories but i'm not getting all child categories but not getting related products. As seen in below images product array is empty, there is some relation issue. Please help to resolve. enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire