Create a Laravel Request object on the fly

Creating a request object with $myRequest = new Request(); creates the object with method = 'GET'. You can check your request's method with $myRequest->getMethod(). As the request property holds data for POST requests you cannot use $myRequest->request->add() by default. First you have to set the request's method to POST:

$myRequest = new \Illuminate\Http\Request();
$myRequest->setMethod('POST');
$myRequest->request->add(['foo' => 'bar']);
dd($request->foo);

By the way using $myRequest->query->add() you can add data to a GET request.


You can use replace():

$request = new \Illuminate\Http\Request();

$request->replace(['foo' => 'bar']);

dd($request->foo);

Alternatively, it would make more sense to create a Job for whatever is going on in your second controller and remove the ShouldQueue interface to make it run synchronously.

Hope this helps!


You can clone the existing request and fill it with new data:

$request = (clone request())->replace(['foo' => 'bar']);

To "avoid duplicate code" you need to abstract the common functionality into a dedicated class, give it a proper mnemonic name, write a set of unit tests around it, and then mock it in controllers when unittesting controllers.

but if you still need to make requests:

use Illuminate\Http\Request;

$request = new Request([
        'name'   => 'unit test',
        'number' => 123,
    ]);

and if you need the full functionality of the Request, you need to add some extra lines

$request
    ->setContainer(app())
    ->setRedirector(app(\Illuminate\Routing\Redirector::class))
    ->validateResolved();