Laravel 控制器类型提示
Laravel Controller Type Hinting
使用-mcr (php artisan make:model Institution -mrc) 创建模型后,controller 中的 show 函数搭建为:
/**
* Display the specified resource.
*
* @param \App\Organization\Institution $institution
* @return \Illuminate\Http\Response
*/
public function show(Institution $institution)
{
return view('institutions.show', ['institution' => $institution]);
}
return 视图... 是我插入的。我期待它用在参数中发送了 id 的对象填充它。
/institutions/1
但是,在使用 dd($institution) 之后,我验证了它有 ID,而不是对象。
这个变量 return 我不应该是对象吗?
这叫做Route Model Binding。您的路线需要类似于:
Route::get('institutions/{institution}', 'InstitutionController@show');
然后根据您的控制器
public function show(Institution $institution)
{
return view('institutions.show', compact($institution))
}
您可以阅读更多相关内容 here。
我想你的路由有一个名为 {id}
的参数,而不是 {institution}
。
替换show函数的参数
public function show(Institution $institution)
{
return view('institutions.show', compact($institution))
}
变成
public function show($id)
{
$institution = App\Institution::findOrFail($id);;
return view('institutions.show', compact('institution'));
}
在你的路线中
Route::get('institutions/{id}', 'InstitutionController@show');
使用-mcr (php artisan make:model Institution -mrc) 创建模型后,controller 中的 show 函数搭建为:
/**
* Display the specified resource.
*
* @param \App\Organization\Institution $institution
* @return \Illuminate\Http\Response
*/
public function show(Institution $institution)
{
return view('institutions.show', ['institution' => $institution]);
}
return 视图... 是我插入的。我期待它用在参数中发送了 id 的对象填充它。
/institutions/1
但是,在使用 dd($institution) 之后,我验证了它有 ID,而不是对象。
这个变量 return 我不应该是对象吗?
这叫做Route Model Binding。您的路线需要类似于:
Route::get('institutions/{institution}', 'InstitutionController@show');
然后根据您的控制器
public function show(Institution $institution)
{
return view('institutions.show', compact($institution))
}
您可以阅读更多相关内容 here。
我想你的路由有一个名为 {id}
的参数,而不是 {institution}
。
替换show函数的参数
public function show(Institution $institution)
{
return view('institutions.show', compact($institution))
}
变成
public function show($id)
{
$institution = App\Institution::findOrFail($id);;
return view('institutions.show', compact('institution'));
}
在你的路线中
Route::get('institutions/{id}', 'InstitutionController@show');