you have to do something like this:
$product = Product::with('category')->get();
return view('products.index')->with('products', $products);
This is called Eager loading. The code above will load all products and return its category as well. To access this in your view you wil have to do something like this:
@foreach ($products as $product)
<p>This my product name {{ $product->name }}</p>
<p>This my product category {{ $product->category->name}}</p>
@endforeach
From your post you could do something like this:
$categories = Category::with('products')->get();
return view('products.index')->with('categories', $categories);
In your view,,
@foreach ($categories as $category)
<h1>$category->name</h1>
<ul>
@foreach ($category->products as $product)
<li>{{ $product->name }}</li>
@endforeach
</ul>
@endforeach
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community