在 Laravel 中的控制器方法签名中省略不必要的变量

问题描述 投票:0回答:1

我经常使用多域应用程序(例如多租户),这些应用程序在使用route()时要求域成为URL的一部分。因此,需要域名作为路由参数,在routes/web.php中定义如下:

Route::group([
    'domain' => '{domain}',
], function () {
    Route::get('{someModel}', [\App\Http\Controllers\SomeModelController::class, 'show']);
// ... some other routes
});

RouteServiceProvider.php:

Route::model('someModel', SomeModel::class);

SomeModelController.php:

// this works but needs the $domain variable in the signature that is not needed in the code below
public function show(string $domain, SomeModel $someModel): JsonResponse
{
    return response()->json($context);
}

// this is what I want to be using, but causes an error: "Argument #1 ($someModel) must be of type App\Models\SomeModel, string given"
public function show(SomeModel $someModel): JsonResponse
{
    return response()->json($context);
}

如图所示,某些控制器方法不需要 $domain 变量(而其他方法则需要)。但是,需要注入变量,因为控制器期望变量的顺序与路由定义链中的顺序相同。我确实明白错误来自哪里,但我认为我在设置依赖项注入(DI)时遗漏了一些东西,因为不需要 $domain。 DI 应该能够通过变量名“someModel”看到这里不需要域。 由于多种原因,我不想从路由参数中删除域。如果不需要,我只想在控制器方法签名中省略它。 有谁知道怎么办吗

laravel
1个回答
0
投票

如图所示,某些控制器方法不需要 $domain 变量(而其他方法则需要)。

在这种情况下,您应该在路线组之外定义您的路线。

Route::group([
'domain' => '{domain}',
], function () {....

有关更多信息,请参阅链接的官方文档..

https://laravel.com/docs/11.x/routing#route-group-subdomain-routing

© www.soinside.com 2019 - 2024. All rights reserved.