'Laravel, how to show a related table's associated name in my home.blade.php?
I know the question might be unclear, but let me elaborate. I have a home page for my website (home.blade.php), where I list the items like this.
@foreach ($products as $product)
<div class="m-auto text-center">
<h2>
<a href="/products/{{ $product->id }}">
{{ $product->name }}
</a>
</h2>
<p>
Manufacturer: {{ $product->manufacturer }}
</p>
<p>
Price: {{ $product->price }}
</p>
<p>
In stock: {{ $product->stock }}
</p>
<a href="seller/{{ $product->sellerID }}">
Seller's site
</a>
<hr>
</div>
@endforeach
I want to show the name attribute of my seller table instead of the Seller's site. With the product table, it's in a many-many relationship. And I store a sellerID attribute in my product table as a foreign key, which references the seller's table id attribute. As for my HomeController.php, the function currently passing the values looks like this.
public function index()
{
$products = Product::all();
return view('home', [
'products' => $products
]);
}
I know that I shouldn't do a query in any view, but I can't figure out how I should do the query in the controller. Can someone help me with this? Also, please ignore the bad-looking site, I'm currently trying to do the backend first, and the frontend comes later.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
