简体   繁体   中英

Laravel Route Regex Alternative Rule Not Working

So, im using a regex for handling parameters on my route, but i cant seem to make 2 rules on my page var to work together. Here is my code

Route::get('/{page}', 'Backend\PageController@viewPage')->where(['type' => 'blog|site', 'page' => '^add$|^[0-9]+$']);

Edit: (the route rule is inside a route group, for some who are wondering where the type var came from, its from the parent route group)

i want to accept either the string "add" or integers , but it seems to accept only the first expression (I tried swapping the position of the expression, only the first works).

Any idea whats the problem? since my type var also has a regex to accept 2 words. Im runnin on Laravel 5.2 and im just starting on laravel. Thanks

Update

tried

Route::get('/{page}', 'Backend\\PageController@viewPage')->where(['type' => 'blog|site', 'page'=>'^add$|^test$']);

to make sure that the problem isnt caused by the 2nd expression pattern, still working for the first expression only

Laravel router (inheriting Symfony router) adds beginning and end of string anchors ( ^ , $ ) accordingly to each where constraint regular expression while removing any existing ones . If alternatives are used in a regular epxression | then whole pattern is enclosed in parentheses.

So in your case, last compiled RegEx would be something like this:

#^/(?:add$|^[0-9]+)$#s

FYI first slash / is caught from route itself. Now if you take a look at what this RegEx brings you, you will notice that there is a misplaced caret ^ in middle of pattern which denotes to a beginning and that never happens.

A solution would be changing your RegEx to this:

add|[0-9]+

Which will be compiled to:

#^/(?:add|[0-9]+)$#s

Larave route:

Route::get('/{page}', 'Backend\PageController@viewPage')
    ->where(['page' => 'add|[0-9]+']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM