rahmatawaludin's avatar

Route global pattern in RouteServiceProvider not working in Laravel 5

Hi all!

I'm working on global pattern in Laravel 5. I've Here is my sample route:

Route::get('welcome/{name}', function($name) {
    return "Welcome " . $name;
});

As stated in doc I should add global pattern to boot method in RouteServiceProvider. Then make it like this:

public function boot(Router $router)
{
    parent::boot($router);
    $router->pattern('name', '[A-Za-z]+');
}

Its not working. then I change it to this:

public function boot(Router $router)
{
    $router->pattern('name', '[A-Za-z]+');
    parent::boot($router);
}

Its still not working. Then I move this to map method like this:

public function map(Router $router)
{
    $router->pattern('name', '[A-Za-z]+');
    $router->group(['namespace' => $this->namespace], function($router)
    {
        require app_path('Http/routes.php');
    });
}

Still not working. If I move it to bottom like this:

public function map(Router $router)
{
    $router->group(['namespace' => $this->namespace], function($router)
    {
        require app_path('Http/routes.php');
    });
    $router->pattern('name', '[A-Za-z]+');
}

Its still not working.

I test it using local server by accesing http://localhost:8000/welcome/jon2323. It should run error, but it isn't. I even create a new Laravel 5 app to test this.

Its only working if I add this line to app/Http/routes.php:

Route::pattern('name', '[A-Za-z]+');

Do I miss something here? I thought it should work if I add those line to RouteServiceProvider.

Thanks.

0 likes
5 replies
eszterczotter's avatar

The regex [A-Za-z]+ matches the 'jon' in 'jon2323', so this is why it won't fail. You probably meant ^[A-Za-z]+$. However, patterns in the boot method won't work, despite what the doc says, but they work in the map method, before the actual routes (your third approach).

1 like
rahmatawaludin's avatar

As stated in my question, If I add the regex to app/Http/routes.php like this

Route::pattern('name', '[A-Za-z]+');

The request to http://localhost/welcome/jon2323 is fails as it should. As stated above, its not working if I place $router->pattern('name', '[A-Za-z]+'); in map() or boot() method in RouteServiceProvider. Is there something I do wrong?

Thanks.

eszterczotter's avatar

Oh, sorry. I just noticed you have 'nama' and 'name'. Could that be why?

Please or to participate in this conversation.