Reputation: 855
I have a Laravel collection with the list of items in the user's cart. Below is my code for fetching that collection:
$items = Cart_Item::all();
$user = JWTAuth::parseToken()->toUser();
$items = $items->where('user_id', $user->id);
$items = $items->map(function ($item, $key) {
return collect($item)->except(['user_id', 'ip_address', 'created_at', 'updated_at'])->toArray();
});
With this I get the following output:
{
"data": [
{
"id": 1,
"product_id": 1,
"quantity": 2
}
]
}
Now in this I want to replace the product_id
with my actual product name using the product
model and also add a field named price
using the product_pricing
model. How can I do this?
Upvotes: 0
Views: 285
Reputation: 14027
If you have the relationships setup correctly, you could do:
$items = $items->map(function ($item, $key) {
$product = Product::with('price')->where('id', $item->product_id)->first();
return [
'id' => $item->id,
'product_id' => $item->product_id,
'quantity' => $item->quantity,
'name' => $product->name,
'price' => $product->price->amount,
];
});
Or the manual inner join way:
$product = Product::select('*')
->join('product_pricing as pp', 'pp.product_id', '=', 'product.id')
->where('product.id', $item->product_id)
->first();
Upvotes: 1