I\'m stuck on this what seems like a simple task.
I have a User that has many Shops that have many Products..
I\'m trying to get all the Pr
what you need is a relationship between the User Model and the Product Model ..
this is possible using hasManyThrough
relationship ..
USER MODEL
public function products()
{
return $this->hasManyThrough('App\Product', 'App\Shop')
}
now, you can access all the user's products with
Auth::user()->products;
You can use this :
\Auth::user()->shops()->with('products')->get()->pluck('products')->flatten();
if you don't want replicate, you can use ->unique()
In this case you can use lazy eager loading:
auth()->user()->load('shops.products');
To iterate over products:
@foreach (auth()->user()->shops as $shop)
@foreach ($shop->products as $product)
{{ $product->name }}
@endforeach
@endforeach
If you need just products:
Product::whereHas('shop', function ($q) {
$q->where('user_id', auth()->id());
})->get();
In both cases, you'll have the same number of queries to DB, so I'd use the first example in a real app.
Assuming that your product model has the shop id stored, try the following:
Products::whereIn('id_shop',
Shops::select('id')
->where('id_owner_user',Auth::user()->id)
->get())
->get()
It will retrieve a collection of products that belong to the list of shops which belong to the authenticated user