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

前端 未结 8 1182
时光取名叫无心
时光取名叫无心 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 03:39

    Edit: There has been some confusion since the release of Laravel 4 regarding this topic, this answer was targeting Laravel 3.

    There are a few ways to approach this.

    The first method is matching (:any)/(:all?):

    Route::any('(:any)/(:all?)', function($first, $rest=''){
        $page = $rest ? "{$first}/{$rest}" : $first;
        dd($page);
    });
    

    Not the best solution because it gets broken into multiple parameters, and for some reason (:all) doesn't work by itself (bug?)

    The second solution is to use a regular expression, this is a better way then above in my opinion.

    Route::any( '(.*)', function( $page ){
        dd($page);
    });
    

    There is one more method, which would let you check if there are cms pages even when the route may have matched other patterns, provided those routes returned a 404. This method modifies the event listener defined in routes.php:

    Event::listen('404', function() {
        $page = URI::current();
        // custom logic, else
        return Response::error('404');
    });
    

    However, my preferred method is #2. I hope this helps. Whatever you do, make sure you define all your other routes above these catch all routes, any routes defined after will never trigger.

提交回复
热议问题