Search code examples
laravellaravel-routinglaravel-5.4laravel-spark

How to exclude slugs from a Laravel route pattern


I have a Laravel Spark application, and would like to use the first two parameters in a route for team and project, with exceptions like about_us, settings, api etc.

I have set up my routes, similar to:

Route::pattern('team', '[a-zA-Z0-9-]+');
Route::pattern('project', '[a-zA-Z0-9-]+');

Route::get('/home', 'HomeController@show');

Route::group(['prefix' => '{team}'], function () {
    Route::get('/', 'TeamController@dashboard');
    Route::group(['prefix' => '{project}'], function () {
        Route::get('/', 'ProjectController@dashboard');
        ...

//Spark defines routes such as /settings after the apps routing file is processed;
//thus I cannot route to /settings as it's caught by /{team}.

I am struggling to do one of two things. Either, exclude values like 'api', 'settings' etc from the {team} pattern; or get the Laravel Spark routes to run before my web routes, so that I can ensure all valid routes are checked before the catch-all of /{team}.

Any ideas would be appreciated!


Solution

  • I appear to have solved it, using the following pattern:

    Route::pattern('team', '(?!^settings$)([a-zA-Z0-9-]+)');
    

    For those who are new to the question, the principles are as follows. In a plain Laravel installation, you could re-order your routes to ensure they are processed in the right order, putting wildcards after your fixed routes.

    With Spark, there are a number of routes all encapsulated away in the Spark package. Preferring not to mess around with this, allowing for easier Spark upgrades later amongst other things, it is possible to use a route pattern to limit the acceptable values for your parameter. As such, with some Googling on RegExs, I appear to have found a pattern that will exclude slugs matched by my {team} parameter.

    I believe that adding more exclusions is as easy as inserting a pipe operator.

    This would also obviously work on standard Laravel installations, but re-ordering your routes is probably a better first call.