Home » Php » php – How to pass parameter to implicit controller in Laravel 5?

php – How to pass parameter to implicit controller in Laravel 5?

Posted by: admin July 12, 2020 Leave a comment

Questions:

In both laravel 4.2 and laravel 5.3, there is an option in route to use implicit controller. The syntax are the same for both version.

Route::controller('myroute', 'myDearController');

So the URL will be:

http://my.domain.com/myroute/function-name/parameter1/parameter2

In laravel 4, the controller will look like:

//..... Some other controller related syntax ......
public function getFunctionName($parameter1, $parameter2) {
    $inputs = Input::all();
    dd($inputs);
}
//..... Some other controller related syntax ......

However, in laravel 5, to get the GET input, it takes up a parameter place, so I tried to make something like this:

//..... Some other controller related syntax ......
public function getFunctionName(Request $request, $parameter1, $parameter2) {
    $inputs = $request->all();
    dd($inputs);
}
//..... Some other controller related syntax ......

However, the URL returns The site can't be reached. I tried switching the position,

//..... Some other controller related syntax ......
public function getFunctionName( $parameter1, $parameter2, Request $request) {
    $inputs = $request->all();
    dd($inputs);
}
//..... Some other controller related syntax ......

It does not work. I know I can add the line Route::get('myroute/function-name/{$parameter1}/{$parameter2}', '[email protected]') to the route file, but besides explicitly specify in the route file, is there a default way to do so?

How to&Answers:

With explicit routes, it should be {parameter} instead of {$parameter}.
so,

Route::get('myroute/function-name/{parameter1}/{parameter2}', '[email protected]')

Answer:

You can’t use ::controller anymore, so you’ll need to create explicit routes for Laravel 5 apps and there is no default way to do what ::controller did in 4.2. You can look at Resource controllers which allow you to use some implicit routes for CRUD.

Laravel resource routing assigns the typical “CRUD” routes to a controller with a single line of code.

Answer:

Route::resource('myroute', 'myDearController');

If you then do php artisan route:list you’ll see a list of all your routes.