【发布时间】:2021-05-24 23:34:24
【问题描述】:
我正在尝试使用 Laravel 的路由模型绑定。我在 RoutesServiceProvider 中设置了一个绑定来执行一些自定义解析逻辑。这适用于需要字符串名称和 id 来解析的 attributable 参数。
但是,当我尝试键入强制转换方法以利用另一个模型的隐式绑定时,它会失败并出现错误
传递给 Illuminate\Routing\Router::{closure}() 的参数 2 必须是 App\Models\Staff 的实例,给定字符串,在 /var/www/html/ngj_form/vendor/laravel/framework/ 中调用src/Illuminate/Routing/Route.php 在第 198 行
经过一些调试,我可以看到它在下面的方法定义中将路由的{attrId} 部分作为第二个类型转换参数传递。 ID 是一个字符串,因此它失败了。但是为什么它甚至试图传递这个参数呢?
路线如下所示:
Route::get('/admin/create-staff-payment/{attributable}/{attrId}/staff-member/{staff}/', 'Admin\StaffBalances@granularStaffBalance');
类型转换控制器方法如下所示:
public function granularStaffBalance(Attributable $attributable, Staff $staff)
{
dd('huh?');
}
RouteServiceProvider 看起来像这样:
public function boot()
{
// Bind Attributable (wedding|trial)
Route::bind('attributable', function ($attributable, $route) {
$attributableId = $route->parameter('attrId');
switch($attributable){
case 'wedding':
$attributable = Wedding::class;
break;
case 'trial':
$attributable = Trial::class;
break;
default:
throw new \Exception('Type parameter provided is not supported.'); //TODO change this to 404 redirect
}
return $attributable::where('id', $attributableId)->firstOrFail();
});
...
【问题讨论】:
标签: php laravel route-model-binding