June 23, 2017 at 5:24 pm

Laravel routing

Most, if not all, routing will be done inside the app/routes.php file. Here you’ll already find a very basic example which will be called to view the first template, I’ve extended mine with a few others to experiment a bit.

$router->get('/about', 'PagesController@about');

You can add a pattern to make sure that every level variable you add ({level}) needs to be numeric. This will be used to link a url segment directly to a variable to use inside the function.

Route::pattern('level', '[0-9]+');

Route::get('level/{level}', function($level) 
   return 'You are on level ' . $level . ' out of 99';

Adding a ? inside the level segment will make sure that this level can be empty as well. That way you can have a default page to show as well if there is nothing filled in.

Route::get('levels/{level?}', function($level=null) 
    if($level) {
        return 'You are on level ' . $level . ' out of 99';
    } else {
        return 'You are on level 1 out of 99';

Like with the pattern pre defined before you can also use the where clause and add an array to pre define multiple segment types.

Route::get('user/{id}/{name}', function($id, $name)
    return 'You got in,' . $name . '.';
->where(array('id' => '[0-9]+', 'name' => '[a-z]+'));
0 likes laravel 5 , routing
Share: / / /