How to “artificially” add values to Request array

A few times I encountered a situation – a store() or update() method with Request parameter, but I needed to add some additional value to the request before calling Eloquent functions. So how to do that? Apparently, pretty easy.

Let’s look at the code:

function store(Request $request) 
{
  // some additional logic or checking
  User::create($request->all());
}

What if you need to add additional field to the request with value coming from that additional logic block? It would look like this:

function store(Request $request) 
{
  // some additional logic or checking
  $plan = 123; // some logic to decide user's plan
  $request->request->add(['plan' => $plan]);
  User::create($request->all());
}

See? The general logic is to add an array of key => value to the $request->request property.
Small tip, but hopefully helpful!

Like our articles?
Check out our Laravel online courses!

14 COMMENTS

  1. That’s a bad practise, because all Request instances will have that additional data.

    Why not just do:

    `User::create($request->all() + [‘plan’ => $plan]);`

    or:

    `User::create(array_merge($request->all(), [‘plan’ => $plan]));`

    • `$request->all() + [‘plan’ => $plan]` will not add the ‘plan’ key if it is already exist in a request. The `array_merge`seems more robust , although the plus-operator is much more faster.

    • Do you mean to say that by doing $request->request->add([‘plan’ => $plan]); Then every future request on the server for that user session will contain the additional data?

  2. How about this?

    Add values to the Request array:
    `array_add($request->all(), ‘user_id’, $user->id);`

    Remove values from the Request array:
    `array_except($request->all(), [‘screenshot’, ‘webcam’]);`

  3. After you *artificially* add the parameters, $request->all() doesn’t return the expected result. $request->merge() seems to be a better approach.

  4. In laravel 5.6 we can pass parameters between Middlewares for example:

    FirstMiddleware

    public function handle($request, Closure $next, …$params)
    {
    //some code
    return $next($request->merge([‘key’ => ‘value’]));
    }

    SecondMiddleware

    public function handle($request, Closure $next, …$params)
    {
    //some code
    dd($request->all());
    }

  5. I find this method to be useful within middleware. At the point where I have custom middleware to check if a record exists, or if a record is related to a record, I may add the record to the request.

    I find this helps to be more granular with authorization (helps me when writting for apis).

LEAVE A REPLY

Please enter your comment!
Please enter your name here