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. 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.

use Illuminate\Http\Request;

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

You can also pass an array of data as a second parameter to the create method to populate the request with data.

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

Watch a course Learn object oriented PHP

You can also pass the headers as a third parameter if you want to set custom headers for the request

$headers = ['Content-Type' => 'application/json'];
$request = Request::create('/example', 'GET', [], [], [], $headers);

You can also use other methods like json() or merge() to set the request data.

$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.

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.