1

When we receive a Request object in Laravel, is there a way to modify or add data to it? For instance, could I rename a parameter (not the value, but the parameter name itself) to something else? For example, the input might be called fname but I want to change it to first_name. Or could I add new inputs and values that weren't in the original request?

The reason I ask is that I have a method that accepts a Request object, and expects certain input names. I'd like to be able to reuse the method, but the request input names will be different.

kenshin9
  • 2,215
  • 4
  • 23
  • 38

2 Answers2

0

If you have an Object you can edit and add new items.

$request->url = $new_url;

$request->new_item = 1;

If the object item not exists, then will create automatically, or if it exists, will modify it.

Marc Garcia
  • 1,388
  • 1
  • 9
  • 21
0

Tested @marc-garcia answer, and that will not persist through your script execution. This will...

    // merge defaults into the request.
    // this makes it consistent everywhere (blade, controller...)
    request()->merge([
        // find the request if it exists, second param is the default value
        'reservable' =>request( 'reservable', (self::RESERVABLE_BY_DEFAULT?1:0) )
    ]);

You may also use request()->replace([...]); but that will remove all other parameters from the request and replace it will the array you provide.

Artistan
  • 1,982
  • 22
  • 33