首页 > 解决方案 > 具有可变前缀和条件的 Laravel 路由组

问题描述

我想在 Laravel 中创建一个以变量为前缀的路由组。我也需要设置一些条件。如何正确地做到这一点?

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

此代码应创建 2 条路线:/{hl}/test-1并且/{hl}/test-2where {hl}is limited to (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

解决方案


group调用不返回任何内容,因此没有任何链接。如果您where在调用 to 之前进行调用group,类似于您调用 的方式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';
    });
});

推荐阅读