Laravel: Setting Request Query Parameter Dynamically on Runtime

Sam Ngu
Jan 19, 2021

--

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'];

$request->merge([
'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'];

$request->merge([
'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);
$nreRequest->merge([
'body' => 'heyy'
]);dump($request->body); // expect null

That’s it! Happy coding.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response