How to pass parameter to Laravel route - BOOKC -->

How to pass parameter to Laravel route

Friday, March 24, 2017


In laravel you can pass parameter into the route, the parameter can be pass down to the controller or even the view, you can also add constraint to filter the parameter, pretty cool huh?

Let's say you have a route /home/info/ like this:
Route::get('/home/info', ['uses' => 'InfoController@showInfo', 'as' => 'home.info']);

If you want to pass parameter to the url /home/info/, lets say the parameter is called 'id', so here's what you should do:
Route::get('/home/info/{id}', ['uses' => 'InfoController@showInfo', 'as' => 'home.info']);

To handle the parameter 'id', you need to change the controller like this:
class InfoController extends BaseController {

public function showInfo($id)
{
return View::make('info')->with('id', $id);
}
}

Next on the view, you just can echo like this:
echo $id;

Now you can try pass parameter to url /home/info/1, /home/info/2 and so on. Here's the problem, the parameter input id can be pass as string, this could be trouble since we only want number as parameter.

To accept only number, we need to add constraint to the route, we can add where() statement just like in SQL.
Route::get('/home/info/{id}', ['uses' => 'InfoController@showInfo', 'as' => 'info'])
->where('id', '[0-9]+');

With the route above, it will return error when someone try to put string as parameter, thanks to regular expression route constraint. The more strict regular expression would be '[1-9][0-9]*', this will not accept 0 as the first number.