Monday, February 27, 2017

Replace Product ID with Product Name in Laravel Collection

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?




via JackSlayer94

Advertisement