Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get a collection of relationship items

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 Products for a certain User.

This is working, and is returning the Shops with their Products

\Auth::user()->shops()->with('products')->get(); 

But I need a Collection of only the Products. I tried the following but it's messing up the Query

\Auth::user()->shops()->with('products')->select('products.*')->get(); 

Any idea what I'm doing wrong? Thank you!

like image 334
Miguel Stevens Avatar asked May 11 '17 07:05

Miguel Stevens


1 Answers

You can use this :

\Auth::user()->shops()->with('products')->get()->pluck('products')->flatten(); 

if you don't want replicate, you can use ->unique()

If you want to directly work on a query (for performances):

  Product::whereHas('shops', function($query){     $query->where('user_id', auth()->user()->id);  })->get();  
like image 67
Mathieu Ferre Avatar answered Oct 11 '22 10:10

Mathieu Ferre