4

For simple routes I know I can user where statement. But what about parameters in Route::group() prefix

<?php

Route::get('user/{id}', 'UserController@profile')->where('id', '[0-9]+');

Route::group(['prefix' => 'foo/{bar}'], function() {
    // ...
})->where('bar', '[0-9a-Z]+'); // this won't work
Behzadsh
  • 851
  • 1
  • 14
  • 30

3 Answers3

19

I'm using laravel 5.5. I had same problem and find this question in search.
I've tried to use the solution defined by @lukasgeiter and faced a problem:
The value of $group->getRoutes() was not only the routes of current group.

But I fixed my problem by specifying condition in route group definition.

Route::group([
        'prefix' => 'foo/{bar}',
        'where'  => ['bar' => '[0-9a-Z]+']
    ],
    function() {

    // ...

});

And it worked for me :)

EmiTis Yousefi
  • 363
  • 4
  • 9
7

Out of the box the laravel router doesn't support this. You can use the Enhanced Router package from Jason Lewis or a fork that enables support for Laravel 4.2

Alternatively you can do it yourself. You could basically add the where condition to every route inside the group:

Route::group(['prefix' => 'foo/{bar}'], function() {
    Route::get('/', function(){
        // ...
    })->where('bar', '[0-9a-Z]+');
});

Or do it a bit more dynamic and add this at the bottom of your route group:

Route::group(['prefix' => 'foo/{bar}'], function($group) {
    // ...

    foreach($group->getRoutes() as $route){
        $route->where('bar', '[0-9a-Z]+');
    }
});
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
4

One of possible not perfect solution in my view will be

// Route Model Binding
Route::model('user', 'User');

// Route Constraint Pattern
Route::pattern('user', '[0-9]+');

// Route Definition
Route::get('anything/{user}', 'UserController@anyFunction');
.
.
Route::resource('user', 'UsersController');
Hassan Jamal
  • 694
  • 9
  • 11