当我在laravel 5
文件中使用laravel Route::resource
函数时,我正在使用route.php
,我可以在这样的方法参数中获取模型集合:
//**web.php** file
Route::resource('factors', 'FactorsController');
//called url localhost:8000/factors/1/edit
//**FactorsController**
/**
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit(Request $request, Factor $factor)
{
//$factor is a collection of Factor Model that contains id '1' information in factor table
return view('factors.edit', compact('factor'));
}
这是正确的并且有效,但是当我这样创建自定义网址时:
Route::get('factors/{id}/newEdit', 'FactorsController@newEdit');
我无法在方法参数中获取集合,并且它返回空集合,如下所示:
//called url localhost:8000/factors/1/newEdit
1)
//**FactorsController**
/**
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function newEdit(Request $request, Factor $factor)
{
return view('factors.newEdit', compact('factor'));
}
$factor
是Factor Model
的一个空集合,但我希望在数据库中选择行。当我使用像这样的作品正确:
2)
//**FactorsController**
/**
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function newEdit(Request $request, $id)
{
$factor = Factor::find($id);
return view('factors.newEdit', compact('factor'));
}
但我不想像2那样称呼它
感谢您的帮助。
答案 0 :(得分:1)
对于model binding,您应该使带有类型提示的变量名称与路由段名称相匹配:
Route::get('factors/{factor}/newEdit', 'FactorsController@newEdit');
由于$factor
变量是Factor
模型的类型提示,并且变量名称与{factor}
URI段匹配,因此Laravel将自动注入ID匹配请求URI中的相应值。