Mahmoud Khosravi
Mahmoud Khosravi

Reputation: 496

Merge into one collection

I want to retrieve multiple records including details from the pivot table into one table. At the moment I have to show a table for each model with the respective rows from the pivot table.

This is what I have in my Controller:

$shops = Shop::where('user_id', auth()->user()->id)->with('products')->get();
return view('shop.pindex')->with('shops', $shops);

in my view I, therefore, have to have the following:

@foreach ($shops as $shop)

    {{$shop->name}} 
    
    @foreach($shop->products as $product)
        Table 

            {{$product->pivot->qty}}

        End Table
    @endforeach

@endforeach

Essentially I just want one table that shows something like:

Shop Name       | Product Name          |   SKU     | qty
Shop A          | Flask                 |   AAA     |   5
Shop A          | Bottle                |   ABB     |   6
Shop B          | Flask                 |   AAA     |   15

Upvotes: 1

Views: 90

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

Then use a join query instead of loading relations

$shops = DB::table('shops as s')
           ->join('products as p', 's.id', '=', 'p.shop_id')
           ->where('s.user_id', auth()->user()->id)
           ->select(['s.name as shop_name','p.name as product_name','p.sku','p.qty'])
           ->get();

Upvotes: 1

Related Questions