W3docs

Create a Laravel Request object on the fly

In Laravel, you can create a Request object on the fly by using the create method of the Request facade.

In Laravel, you can create a Request object on the fly by using the create method of the Request facade. This approach is primarily intended for unit testing or internal request simulation. The create method accepts the URI of the request and the HTTP method as its arguments. The Request object can then be used as a parameter in a controller method or middleware.

Example of creating a Request object on the fly by using the create method of the Request facade in Laravel

use Illuminate\Http\Request;

$request = Request::create('/example', 'GET');

You can also pass an array of GET query parameters as the third argument, and POST/request body data as the fourth argument to populate the request.

Example of passing an array of data as the fourth parameter to the create method of the Request facade in Laravel

$data = ['name' => 'John', 'email' => '[email protected]'];
$request = Request::create('/example', 'POST', [], $data);

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can also pass custom headers in the $server array (eighth argument) using the HTTP_ prefix.

Example of passing the headers via the $server array to the create method of the Request facade in Laravel

$server = ['HTTP_CONTENT_TYPE' => 'application/json'];
$request = Request::create('/example', 'GET', [], [], [], [], [], $server);

You can also use the merge() method to add or update request data.

Example of using the merge() method to set the request data in Laravel

$request->merge(['name' => 'John']);

This request object can now be passed to a controller method or middleware as if it was an actual incoming request.

Example of passing the request object to a controller method or middleware in Laravel

public function example(Request $request)
{
    $name = $request->input('name');

    // Do something with the request data
}

It's important to note that this request object is only valid for the current request lifecycle and will not persist between requests.