Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set regular expression parameter constraints for Route::group in Laravel 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
like image 713
Behzadsh Avatar asked Nov 28 '22 16:11

Behzadsh


2 Answers

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 :)

like image 73
EmiTis Yousefi Avatar answered Dec 04 '22 04:12

EmiTis Yousefi


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]+');
    }
});
like image 45
lukasgeiter Avatar answered Dec 04 '22 03:12

lukasgeiter