Ad

Cannot Get Children Category Product In Laravel

- 1 answer

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,

My table Structure are as follows:

Product:

enter image description here

Category:

enter image description here

Product_categories :

enter image description here

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

public function getChildCategories($id)
{
    return Category::with('children','products')->find($id); 
}

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

Output:

enter image description here

Ad

Answer

first of all, remove childrenProdut() as this function is doing the same as children() function.

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

Now In case if I want to get all children i.e subcategories and their products then use the following snippets in the controller.

Category::with(['children' => function($query){
    //the 'children' relationship should be called within an array
    //this way you could query the relationship as the eloquent model.
    //that way you could call the 'products' relationship inside the Category relationship.
    $query->with('products')
}]);
Ad
source: stackoverflow.com
Ad