Home > Back-end >  Laravel, how to show a related table's associated name in my home.blade.php?
Laravel, how to show a related table's associated name in my home.blade.php?

Time:02-14

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 >
        <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.

CodePudding user response:

I'm not sure if I understood you entirely, because I got confused.

If you have many-to-many relationship, you can't have sellerID. Foreing id can be used in one-to-many or one-to-one relationships.

In order to have many-to-many relationship, you need to have a pivot table.

product_seller
id, product_id, seller_id

In conttoller

Product::with('sellers')->get();

In view, there is another problem. You will have many sellers, but you want to display only one, which one? I assume you either have a wrong relationship, or wrong view, or misexplained problem. But if I go based on many to many:

@foreach ($product->sellers as $seller)
    <a href="seller/{{ $seller->id }}">Seller's site</a>
@endforeach
  • Related