Your viewOrders
action should be hidden behind authentication process (obviously, user has to first sign in before he can view his orders). Once you do that (using auth
middleware for it's route), Laravel can resolve authenticated user for you - you can simply hint it as a parameter of your viewOrders
action:
public function viewOrders(User $user)
{
$orders = $user->orders()->orderBy('id', 'desc')->get();
return view('orders')->with(compact('orders'));
}
As you notice, here I've modified your query a little bit. Instead of selecting all orders we are now selecting them through authenticated user's relation to it's orders. Orders obviously belong to user, but through products (as an intermediate) - one user can have many products, one product can have many orders, thus one user can have many orders. In Laravel this kind of relationship between eloquent models is called HasManyThrough. Therefore you should declare it in your User
model:
class User extends Model {
...
public function orders()
{
return $this->hasManyThrough(Order::class, Product::class);
}
}
Note that your Product
will probably also have orders()
relation, but it will be of HasMany
type instead since it's a direct one without any intermediates.