1

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?

2
  • Find is the same as where('id', '=', ?)->first(). Use ->get() and whereIn() instead. Commented Apr 24, 2017 at 16:43
  • Yup, whereIn() solved my problem. Commented Apr 24, 2017 at 17:16

2 Answers 2

3

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'));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks your solution worked. But laravel documentation says that we can use an array as parameter to call find() method to get matching results- laravel.com/docs/5.4/eloquent#retrieving-single-models
Ah, I see that they added that in 5.2. I'll have to remember that.
2

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.