Search code examples
phprequestlaravel-5.1

Create a Laravel Request object on the fly


I'm handling data in one controller and want to pass it further into another controller to avoid duplicate code.

Is there a way to set up a Request object that is needed in the other controller's store-method? I've traced down the Request inheritance and came to Symfony's Request object which has a request property that is in fact a ParameterBag that holds a method add to add parameters with values to it.

I've tried the following but I'm getting null as result:

$myRequest = new Request();
$myRequest->request->add(['foo' => 'bar']);
var_dump($myRequest->foo);

I'm on Laravel 5.1 for this project.


Solution

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