basagabi basagabi - 6 months ago 29
PHP Question

Laravel option route parameter not working

I'm using laravel 5.2 and having problems with regards to routing. Supposed I have this route:

http://example.com/out/parameter1/parameter2/


Parameter1 should be required while Parameter2 should be optional. When user enter this url:
http://example.com/out/parameter1/
or this
http://example.com/out/parameter1/parameter2/
, they should be able to proceed. By when this is entered,
http://example.com/out/
they will be redirected to the homepage.

Here's my route:

Route::get('out/{param1}/{param2?}', 'MyController@out']);
Route::get('out/', 'MyController@redirect']);


The controller:

public function out($param1, $param2 = '', Request $request) {
// logic here
}


The error that I'm getting is this:
Argument 3 passed to App\Http\Controllers\MyController::out() must be an instance of Illuminate\Http\Request, none given


I already specify a default value for
param2
on the method.

Answer

Request instance must be the first one

public function out(Request $request, $param1, $param2 = '') 
{
    // logic here
}

Docs: https://laravel.com/docs/5.2/controllers under Method Injection