tehseen
6 months ago
691
10
Eloquent

fetch & display category and its products

Posted 6 months ago by tehseen

I have relationship many to many between products & categories.

In my Product Model

public function categories() {
    	return $this->belongsToMany(Category::class, 'category_product');
    }

In my Category Model

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

so what i try to get is display category with products just like below image. https://ibb.co/vZy9HDz

each how have 4 categories and then each category display product like in image 2 rows with 4 product each.

in my controller i fetch category with product like below

        $categories = Category::with('products')->get();

Thanks for help in advance

Please sign in or create an account to participate in this conversation.