Search code examples
phplaravelroutesslug

How to create a slug route excluding some slug in laravel routing?


I've following routes currently.

$router->get('/contact-us','HomeController@contactUs')->name('contact-us');
$router->get('/about','HomeController@about')->name('about');

Now, I want to make general pages accessible form following route,

$router->get('/{slug}','SomeController@about')->name('general-page');

But main problem is contact us and about page matched with slug route and wrong controller is called. Is there any way to exclude such slugs from general page route.


Solution

  • You could add a pattern to your route, where the terms contact-us and about are excluded, like this:

    $router->get('/{slug}','SomeController@about')
        ->where('slug', '^((?!about|contact-us).)*$')
        ->name('general-page');
    

    For an explanation of the regex, see here

    In this way the order of the route definitions has no consequence.