Search code examples
phparrayslaravelrequest

Add nested array to Laravel request


I am trying to add to a nested array in a request in my controller. At the moment, my request looks like this:

+request: ParameterBag {#43 ▼
#parameters: array:3 [▼
"_token" => "*****"
"my-event" => array:26 [▼
"title" => "my new event"
"start-date" => "2019-05-01"
 .....

I would like to add to this request in the "my-event" array, e.g. "event-approved" with a value of 0.

I can see that you can add to a request like so:

$request->request->add(['my-key' => 'value']);

But I am unsure on how to do this for a nested array. I would want something like:

$request->request->add(['my-event']['event-approved'] = '0');

But I am getting the error:

Cannot use temporary expression in write context


Solution

  • A better and faster approach is:

    $event = $request->get('my-event');
    $event['event-approved'] = "0";
    $request->request->add(['my-event'=>$event]);
    

    NOTE that it will NOT override any existing fields of my-event array except only set the event-approved field.

    Or if you want a one-liner try:

    $request->request->add(['my-event'=>array_merge($request->get('my-event'),['event-approved'=>"0"])]);
    

    There is no other short-hand method for this kind of manipulation