regexlaravelrouterlumenlumen-routing

How to exclude "/api" from "any"-route in Lumen router (per regex)?


I have a problem with the Lumen router (web.php): My project includes vue.js with the vue router, so I want to point all routes to the router, what is indeed working fine.

$router->get('{path:.*}', function () {
    return view('app');
});

My problem is: I also have a few api routes, handled by Lumen/controllers:

$router->group(['prefix' => 'api'], function ($router) {
    $router->group(['prefix' => 'authors'], function ($router) {
        $router->get('/', 'AuthorController@showAllAuthors');
        $router->get('/id/{id}', 'AuthorController@showAuthorById');
    });
});

Well, the route localhost/api/authors just works fine. But localhost/api/authors/1 returns the app..

I was thinking of putting in an exception to the vue route:

$router->get('{path:^(?!api).*$}'

..but this will lead to a NotFoundHttpException. Is something wrong with the regex? It should exclude all routes that start with /api.


Solution

  • You're really close. Regex happens after the get/post statements in laravel's routes. Like so:

    $router->get('/{catch?}', function () { 
        return view('app'); 
    })->where('catch', '^(?!api).*$');
    

    Here's the docs for reference: https://laravel.com/docs/5.8/routing#parameters-regular-expression-constraints

    Edit: Lumen specific should be solved in a group prefix.

    $router->get('/{route:.*}/', function () { 
        return view('app'); 
    });