2

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

1
  • ['my-event']['event-approved'] = '0' is not a valid parameter you can use in $request->request->add(). Commented Apr 2, 2019 at 9:08

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

I have found a way of doing this but there may be a more efficient way of doing this:

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

$request->merge($requestData);

Comments

0

Try this.

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

3 Comments

$value = ['my-event']['event-approved'] = '0'; is INVALID php syntax!!
this is a copy of my own answer!! Please
This late-edited answer has been altered to mirror the insights of the accepted answer after it was revealed that the initial answer did not work as written. This answer can be safely removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.