This is my products model
public function orders(){
return $this->hasMany(Order::class);
}
and this is my Orders model
public function user(){
return $this->belongsTo(User::class);
}
public function product(){
return $this->belongsTo(Product::class);
}
and my order table structure
this is my response as of now (I'm using Order model).
{
id: 11,
quantity: 2,
customer: {
id: 6,
name: "saging",
email: "saging@gmail.com",
role_id: 3,
},
items: {
id: 7,
name: "Pellentesque semper",
description: "raesent sit amet elementum purus. ",
price: "72.21",
cover_image: "7CPVS7yjqba9iJ7J.jpg",
}
},
{
id: 12,
quantity: 2,
customer: {
id: 6,
name: "saging",
email: "saging@gmail.com",
role_id: 3,
},
items: {
id: 3,
name: "Donec nec mattis ligula",
description: "Pellentesque semper, augue at aliquet tincidunt",
price: "33.21",
cover_image: "ZJbbzjPwDXrcbkwi.jpg",
}
}
the code that im currently using is
$products = Order::with('user','product');
return OrdersResource::collection($products->paginate(5));
and im listing the products and customer
by using the methods in my Order Model
the output that i want is like this
{
id: 12,
quantity: 2,
customer: {
id: 6,
name: "saging",
email: "saging@gmail.com",
role_id: 3,
},
items: [
{
id: 3,
name: "Donec nec mattis ligula",
description: "Pellentesque semper, augue at aliquet tincidunt",
price: "33.21",
cover_image: "ZJbbzjPwDXrcbkwi.jpg",
},
{
id: 7,
name: "Pellentesque semper",
description: "raesent sit amet elementum purus. ",
price: "72.21",
cover_image: "7CPVS7yjqba9iJ7J.jpg",
}
]
}
this is my OrderResource Code
$sub_total = $this->quantity * $this->product->price;
$discount = round((10 / 100) * $sub_total, 2);
$total = $sub_total - $discount;
return [
'id' => $this->id,
'quantity' => $this->quantity,
'address' => $this->address,
'sub_total' => $sub_total,
'discount' => $discount,
'total_price' => $total,
'created_at' => Carbon::parse($this->created_at)->format('F d, Y h:i:s A'),
'customer' => $this->user,
'items' => $this->product,
];
Is my relationship wrong? I'm new to laravel and the eloquent relationship is the part where i always skipped because I'm confuse. But now i have to face it.