Home > Software engineering >  Laravel mapWithKeys() returns single value
Laravel mapWithKeys() returns single value

Time:03-26

In laravel I'm getting products array that looks like this

dd($activity->load('products'));
"products": [

    {
    "id": 1,
    "pivot": {
    "activity_id": 1,
    "product_id": 10,
    "quantity": 16
    }
    },
    {
    "id": 2,
    "pivot": {
    "activity_id": 1,
    "product_id": 11,
    "quantity": 20
    }
    }

]

I want to get an array of objects and pluck only the pivot.product_id and pivot.quantity from the products array

Expected result:

"selected_products": [

    {
    "id": 10,
    "quantity": 16 
    },
    {
    "id": 11,
    "quantity": 20
    }

]

What I tried

return $activity
->load('products')
->products()
->get()
->mapWithKeys(function ($product, $key) {
   return ['id' => $product->pivot->product_id, 'quantity' => $product->pivot->quantity];
});

Result

{
    "id": 10,
    "quantity": 16
}

CodePudding user response:

There are 2 problems on your code.

First, load('products') is redundant. You cam simple call $activity->products. Or if you need filter on the products , use $activity->products()->where(...)->get()

Second, you should use map for indexed array. mapWithKeys is using for associative array.

return $activity->products
->map(function ($product, $key) {
   return ['id' => $product->pivot->product_id, 'quantity' => $product->pivot->quantity];
});
  • Related