Skip to content
Advertisement

Get orders of a user with orderItems and product details in Laravel

I have 3 tables (foods, orders and orderItems). I want to get orders of a user with orderItems and foods, but i failed.

Here’s a result what i am getting right now, but i need to get food details instead of food_id.

[
    {
        "id": 16,
        "user_id": 2,
        "total": "12.50",
        "items": [
            {
                "id": 20,
                "order_id": 16,
                "food_id": 1,
                "quantity": 1,
                "food_price": "12.50",
            }
        ]
    }
]

OrderController

$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items')->get());

User Model

public function deliveredOrders()
{
    return $this->hasMany(Order::class)->where('status', '=', 'delivered');
}

Order Model

public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

Advertisement

Answer

You should define food() method on OrderItem model.

public function food() 
{
   return $this->belongsTo('AppFood');
}

And get relation data using this:

$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items.food')->get());
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement