【问题标题】:How do I make a Catch-All Route in Laravel如何在 Laravel 中创建一条包罗万象的路线
【发布时间】:2016-04-22 05:36:40
【问题描述】:

我需要一个 laravel routes.php 条目,它可以捕获网站特定 domain.com/premium-section 的所有流量,以便在访问高级内容之前提示人们成为会员。

【问题讨论】:

    标签: php laravel routing


    【解决方案1】:

    您还可以通过在参数上使用正则表达式来捕获“全部”。

    Route::group(['prefix' => 'premium-section'], function () {
        // other routes
        ...
        Route::get('{any}', function ($any) {
            ...
        })->where('any', '.*');
    });
    

    如果没有使用可选参数定义路由,也可以捕获整个组。

    Route::get('{any?}', function ($any = null) {
        ...
    })->where('any', '.*');
    

    最后一个也会捕获“domain.com/premium-section”。

    【讨论】:

    • 感谢您的回答。我想知道为什么 Laravel 没有被编码为使用简单的Route:any('*')
    • 感谢您的解决方案!只是一个提示,最好不要使用闭包,因为它们不能被缓存。 Route::get('/{action}', 'SiteController@defaultPageHandler')->where('action', '.*'); 会更好;)
    • @LeonidDashko Route::fallback 会更好,因为它只是一个捷径。
    • @lagbox 我猜它们也不能被缓存 :) 但是很高兴知道这个替代方案。
    • Route::fallback 不是闭包,所以可以缓存
    【解决方案2】:

    这就是诀窍:

    Route::any('/{any}', 'MyController@myMethod')->where('any', '.*');
    

    【讨论】:

    • 我总是得到一个“参数太少”的错误编辑:你还需要一个 / 路由,否则点击实际的根主页会导致 500 错误
    • 只需将 ? 添加到参数中,甚至会捕获根 uri 即:{any?}
    【解决方案3】:
    1. 在 app/Http/routes.php 中,我创建了一个路由,它将捕获 domain.com/premium-section/anywhere/they/try/to/go 中的所有流量,并尝试在 PremiumSectionController 中查找并执行匹配函数
    2. 但是没有任何匹配的方法,只是一个包罗万象的方法。

      Route::group(['as' => 'premium-section::',
                    'prefix' => 'premium-section',
                    'middleware' => ['web']],
                    function(){
                       Route::any('', 'PremiumSectionController@premiumContentIndex');
                       Route::controller('/', 'PremiumSectionController');
      
                    });
      

    .

        namespace App\Http\Controllers;
    
        use ...
    
        class PremiumSectionController extends Controller{
    
            public function premiumContentIndex(){
               return 'no extra parameters';
            }
    
            //magically gets called by laravel
            public function missingMethod($parameters = array()){
                return $parameters;
            }
    
        }
    

    【讨论】:

    • 这样该路由将捕获 'domain.com/premium-section/anywhere/they/try/to/go' ?
    • 是的,我把我的 Q 和我的 A 贴在一起了。
    • 如果你需要构建一个redirect()->route('somwhere-else', $withParams),将参数作为一个数组很方便
    【解决方案4】:

    Laravel 现在有一个内置方法:

    https://laravel.com/docs/master/routing#fallback-routes

    【讨论】:

      【解决方案5】:

      这对我有用

      // The catch-all will match anything except the previous defined routes.
      Route::any('{catchall}', 'CatchAllController@handle')->where('catchall', '.*');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-15
        相关资源
        最近更新 更多