Search code examples
laravellaravel-7

Show many products from a category from many-to-many relationship in laravel


So I’m making a catalogue using Laravel 7.* and I have a problem.

I have many products and many categories. I have created a many-to-many relationship so a product can be in many categories.

Now, what I am trying to do is to show in a page each category with related products, but obviously I am doing something wrong.

Below you may see some code:

Product.php:

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

Category.php:

public function product()
{
return $this->belongsToMany(Product::class);
}

Show.blade.php

@php
$products = \App\Product::with('categories')->find(1);
@endphp
@foreach ($products as $id)
{{ $id->name }}<br>
@endforeach

Any help please?


Solution

  • Fixed it.

    I fetched categories in controller and send to view. Then for each category displayed each product.