Level 104
OPTION 1
Your nested resources (user_cart_items) can be a Resource Collection itself.
// UserOrderResource
public function toArray($request)
{
return [
'id' => $this->id,
'paymentMethod' => $this->payament_method,
'receivedType' => $this->recivedType,
'receivedLocation' => $this->reciveLocation,
'created_at' => $this->created_at,
'status' => $this->status,
'user_cart_items' => UserCartItemResource::collection($this->whenLoaded('user_cart_items')),
];
}
// UserCartItemResource
public function toArray($request)
{
return [
'product_name'=>$this->product->name_ar,
'price'=>$this->price,
'qty'=>$this->qty,
];
}
OPTION 2
You would need to map over the Collection of user_cart_items and build up the array representation:
// UserOrderResource
public function toArray($request)
{
return [
'id' => $this->id,
'paymentMethod' => $this->payament_method,
'receivedType' => $this->recivedType,
'receivedLocation' => $this->reciveLocation,
'created_at' => $this->created_at,
'status' => $this->status,
'user_cart_items' => $this->user_cart_items->map(function ($item) {
return [
'product_name'=>$item->product->name,
'price'=>$item->price,
'qty'=>$item->qty,
];
})->all()
];
}
1 like