Reputation: 544
I have three tables - users
, products
and orders
There is a relation between users
and orders
(users
has many orders
).
orders
table contains product_id
and user_id
column.
Now I want to access the product details of orders for a user.
What I am trying:
public function myOrders(){
$orders = Auth::user()->orders->pluck('product_id');
$products = Product::find($orders);
return view('shop.myorders', compact('products'));
}
But this is not working. Can anyone help me? What other way can be better to achieve this?
Upvotes: 1
Views: 8616
Reputation: 163748
I assume you have orders()
relation defined in the Product
model:
public function orders()
{
return $this->hasMany(Order::class)
}
Then you'll be able to load products from all user's orders:
$products = Product::whereHas('orders', function($q) {
$q->where('user_id', auth()->id())
})->get();
Upvotes: 2
Reputation: 23001
As mentioned, find()
will always return 1 item, and expects a string/int for the parameter. You want to use where
and get
instead. With an array of ids, you can use whereIn
.
public function myOrders(){
$orders = Auth::user()->orders->pluck('product_id');
$products = Product::whereIn('id', $orders)->get();
return view('shop.myorders', compact('products'));
}
Upvotes: 3