phplaravellaravel-8laravel-request

Laravel merge field in sub-arrays in the request


I am receiving this data from the request:

array:2 [
  0 => array:3 [
    "from" => 0
    "to" => 5
    "earned" => 0
  ]
  1 => array:3 [
    "from" => 5
    "to" => 10
    "earned" => 1
  ]
]

I would like to add brand_id to each sub-array.

I know that I can merge a field into the request like:

$request->merge([
    'brand_id' => $brand_id,
]);

Which results in:

array:3 [
  0 => array:3 [
    "from" => 0
    "to" => 5
    "earned" => 0
  ]
  1 => array:3 [
    "from" => 5
    "to" => 10
    "earned" => 1
  ]
  "brand_id" => "1"
]

Where I want the result to be:

array:2 [
  0 => array:4 [
    "from" => 0
    "to" => 5
    "earned" => 0
    "brand_id" => "1"
  ]
  1 => array:4 [
    "from" => 5
    "to" => 10
    "earned" => 1
    "brand_id" => "1"
  ]
]

It would be nice if it was possible to do it like:

$request->merge([
    '*.brand_id' => $brand_id,
]);

Note: I have checked this How to replace nested array value inside the Laravel request using merge? but if I'm going to use foreach, I won't need to be doing request merge. Besides maybe there's something new with Laravel 8.


Solution

  • Try below code. You can iterate each elements and merge. (assuming you are using a request object)

    $mergedArray = array_map(function($element) use ($brand_id){ 
        return array_merge($element, ['brand_id' => $brand_id]); 
    }, $request->all())