Chron's avatar

How to append data on request array

I tried doing this

// if there are no `available` keys found in `cars` request, set the first item to true
if(!collect($request->input('cars'))->contains('available', true)) {
   $request['cars'][0] = ['available'=>true];
}

But I'm getting Indirect modification of overloaded element.... I can use collect(...)->transform(...) but is there a shorter and faster way of doing it.

0 likes
3 replies
Glukinho's avatar
Level 30
  1. there is a collection method doesntContain():
if (!collect()->contains(...)) // so-so

if (collect()->doesntContain(...)) // a little more beautiful
  1. can you show full request example?

  2. is it what you asked? https://laravel.com/docs/12.x/requests#merging-additional-input

if ( $request->collect('cars')->doesntContain('available', true) ) {
	$request->merge([
		'cars' => [
			0 => [ 'available' => true ]
		]
	]);
}
Chron's avatar

Here's the structure

  "cars" => array:2 [
    [
		"name" => "A3",
		"brand" => "Audi",
		"available" => true
    ],
    [
		"name" => "C40",
		"brand" => "Volvo",
    ],
  ]

Now, if the available does not exists, I want to add it to the first item of the cars array

Glukinho's avatar

Check code I provided earlier, I think it is what you need.

Please or to participate in this conversation.