Laravel: Setting Request Query Parameter Dynamically on Runtime

Photo by darlene on Unsplash

Setting request query parameter can be very useful, especially in testing. We can set the request query parameter on runtime using the $request->merge() function. Here’s how:

/** @var $request \Illuminate\Http\Request */
$request = app()['request'];

'page' => '3'
dump($request->page); // expect: '3'

In Testing Classes, we should access the app instance via $this->app :

// TestClass extending TestCase/** @var $request \Illuminate\Http\Request */
$request = $this->app['request'];

'page' => '3'

The merge function will modify the current request in-place. If you want to clone the request, you can use the \Illuminate\Support\Facades\Request::createFrom() function

For example:

$request = app()['request'];// cloning the request so we don't modify the source

$newRequest = \Illuminate\Support\Facades\Request::createFrom($request);
'body' => 'heyy'
]);dump($request->body); // expect null

That’s it! Happy coding.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store