Search code examples
requestparameter-passinglaravel-8php-8

Laravel 8+, pass request into route manually, is it possible?


I have a Laravel 8 project. I have a route:

Route::get('/route-path', 'Client\SomeController@someMethod')->name('MyRouteName');

And it's implementation in SomeController

public function someMethod(Illuminate\Http\Request $request)
{
    $field_1 = $request->f1;
    $field_2 = $request->f2;

    return view('my_view', compact('field_1', 'field_2'));
}

I'd like to redirect my site into MyRouteName route, but I'd like to create request manually:

$request = new Illuminate\Http\Request();
$request->request->add([
    'f1' => 'value_1',
    'f2' => 'value_2',
]);

return redirect()->route('MyRouteName', $request);

Is it possible to pass fake request this way? If not, how to achieve it?

Thanks! Mike

I'm inside of writing larger part of code, at this point I cannot test. I'll be humbly thank for advices. Thank you.


Solution

  • In Laravel, you cannot directly pass a Request object to the redirect()->route() method. The redirect()->route() method expects parameters that correspond to route parameters, not a full Request object.

    However, you can pass query parameters or simply add the data to the redirect URL. Here’s how you can achieve that:

    Option 1: Pass Parameters Directly You can pass the parameters directly in the redirect like this:

    return redirect()->route('MyRouteName', [ 'f1' => 'value_1', 'f2' => 'value_2', ]);

    Option 2: Using Query Parameters If your route is expecting query parameters, you can add them as such:

    return redirect()->route('MyRouteName', [ 'f1' => 'value_1', 'f2' => 'value_2', ]);

    Option 3: Using Flash Data If you need to preserve the values in the session and access them in your controller, you can use flash data:

    $request->session()->flash('f1', 'value_1'); $request->session()->flash('f2', 'value_2');