Laravel - Using (:any?) wildcard for ALL routes?

前端 未结 8 1149
时光取名叫无心
时光取名叫无心 2020-11-29 03:18

I am having a bit of trouble with the routing.

I\'m working on a CMS, and i need two primary routes. /admin and /(:any). The admin

相关标签:
8条回答
  • 2020-11-29 04:02

    Laravel 5

    This solution works fine on Laravel 5:

    Route::get('/admin', function () {
    
      // url /admin
    
    });
    
    Route::get('/{any}', function ($any) {
    
      // any other url, subfolders also
    
    })->where('any', '.*');
    

    Lumen 5

    This is for Lumen instead:

    $app->get('/admin', function () use ($app) {
      //
    });
    
    $app->get('/{any:.*}', function ($any) use ($app) {
      //
    });
    
    0 讨论(0)
  • 2020-11-29 04:02

    Hitting a 404 status seems a bit wrong to me. This can get you in all kind of problems when logging the 404's. I recently bumped into the same wildcard routing problem in Laravel 4 and solved it with the following snippet:

    Route::any('{slug}', function($slug)
    {
        //do whatever you want with the slug
    })->where('slug', '([A-z\d-\/_.]+)?');
    

    This should solve your problem in a controlled way. The regular expression can be simplified to:

    '(.*)?'
    

    But you should use this at your own risk.

    Edit (addition):

    As this overwrites a lot of routes, you should consider wrapping it in an "App::before" statement:

        App::before(function($request) {
                //put your routes here
        });
    

    This way, it will not overwrite custom routes you define later on.

    0 讨论(0)
提交回复
热议问题