Laravel routes accepts only specific format

时间:2015-09-30 23:16:50

标签: php regex laravel laravel-4 laravel-5

I'm using laravel 5.1 and I would like to know if I could only allow specific route format in my routes.php?

The route format should look like this (strict):

http://example.com/archive/2015-09

Wherein 2015-09 is year-month. It should only accept this format (as stated above). Having a different format will only redirect to the homepage. Example:

http://example.com/archive/2015
http://example.com/archive/asd
http://example.com/archive/2015-9
http://example.com/archive/2
http://example.com/archive/2015-09-01

So in my routes I have this:

Route::get('archive/{date}', 'ArchiveController@index');

I saw on the documentation that regular expressions could be used but I'm not sure how would I be able to do it.

1 个答案:

答案 0 :(得分:1)

这就是你想要的:

Route::get('archive/{date}', function(){
    // Your code
})->where(['date' => '[0-9]{4}-[0-9]{2}']);;

这将匹配......

  • 数字从0到9,恰好是4次
  • 后跟连字符-
  • 后跟数字0到9,恰好两次

请注意,这并不能保证日期不会像“9999-99”那样错误,但您可以在控制器中进行这些检查。