Using a regex to match a substring in a Laravel route

13,907

I got it working with ^([0-9A-Za-z\-]+)?bar([0-9A-Za-z\-]+)?

So the updated route code looks like this:

Route::any('{myslug}/page/', array('as'=>'bar-page', 'uses'=>'Controllers\MyBar@index'))
 ->where('myslug','^([0-9A-Za-z\-]+)?bar([0-9A-Za-z\-]+)?');

Bonus: To make it case insensitive, I do this: ^([0-9A-Za-z\-]+)?(?i)bar([0-9A-Za-z\-]+)?

Note: If you are using a copy of this route further down in the your routes file, but searching for a different sub-string then you will need to name your {myslug} to something different like {myslug2}, otherwise Laravel will not run all of the routes.

Share:
13,907
prograhammer
Author by

prograhammer

David Graham Developing web applications for The Home Depot.

Updated on June 19, 2022

Comments

  • prograhammer
    prograhammer almost 2 years

    My URL is: www.foo.com/some-bar-slug-here/page

    I can't get a route to catch if the string "bar" is found in the slug shown above:

    Route::any('{myslug}/page/', array('as'=>'bar-page', 'uses'=>'Controllers\MyBar@index'))
         ->where('myslug','/bar/');
    

    If I use the regex expression [0-9A-Za-z\-]+ it works, but it doesn't work for /bar/. Any ideas?

  • Qh0stM4N
    Qh0stM4N about 6 years
    did you refer to a resource on why we don't use standart regEx?