lundi 6 avril 2020

Get current category with children categories laravel

I'm getting children category with the help of following relation :

Category Model:

 public function childrenProdut()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

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

Category Controller:

$productsLists = Category::with(['children' => function($query) use
 ($categorySlug) {
         $query->with('products');
     }])->where('slug',$categorySlug)->get();

     return $productsLists;

I'm getting children category and product of the children category of the parent category but a scenario arise where i do not have children category and i have product inside the main category on which user clicks so in that case also i want the category on which the user clicks and their associated product.

Output:

No Child Category Exists

enter image description here

Child Category Exists

enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire