我正在尝试使用 Laravel 的路由模型绑定。我在 RoutesServiceProvider 中设置了一个绑定来执行一些自定义解析逻辑。这适用于attributable
需要字符串名称和 id 来解析的参数。
但是,当我尝试键入强制转换方法以利用另一个模型的隐式绑定时,它会失败并出现错误
传递给 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();
});
...