【问题标题】:Laravel route group with variable prefix and where condition具有可变前缀和条件的 Laravel 路由组
【发布时间】:2021-10-25 00:57:37
【问题描述】:

我想在 Laravel 中创建一个以变量为前缀的路由组。我也需要设置一些条件。怎么做才合适?

我关注的是文档:https://laravel.com/docs/8.x/routing#route-group-prefixes,但只有一般示例。

此代码应创建 2 个路由:/{hl}/test-1/{hl}/test-2,其中 {hl} 仅限于 (en|pl),但它会给出错误:"Call to a member function where() on null"

Route::prefix('/{hl}')->group(function ($hl) {

    Route::get('/test-1', function () {
        return 'OK-1';
    });

    Route::get('/test-2', function () {
        return 'OK-2';
    });

})->where('hl','(en|pl)');

【问题讨论】:

标签: laravel


【解决方案1】:

group 调用不返回任何内容,因此没有任何链接。如果在调用group 之前调用where,类似于调用prefix,它将建立这些属性,然后当你调用group 时,它将级联到组中的路由:

Route::prefix('{hl}')->where(['h1' => '(en|pl)'])->group(function () {
    Route::get('test-1', function () {
        return 'OK-1';
    });

    Route::get('test-2', function () {
        return 'OK-2';
    });
});

【讨论】:

    【解决方案2】:

    类比this answer

    Route::group([
        'prefix' => '{hl}',
        'where' => ['hl' => '(en|pl)']
    ], function ($hl) {
        Route::get('/test-1', function () {
            return 'OK-1';
        });
        Route::get('/test-2', function () {
            return 'OK-2';
        });
    });
    

    这能解决您的问题吗?

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 2017-03-13
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2017-07-20
      • 2018-01-08
      相关资源
      最近更新 更多