laravel资源功能可以正常工作,但是当我手动使用它时却无法正常工作

时间:2020-10-24 11:47:10

标签: laravel laravel-routing

当我在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'));
 }

$factorFactor 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那样称呼它

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

对于model binding,您应该使带有类型提示的变量名称与路由段名称相匹配:

Route::get('factors/{factor}/newEdit', 'FactorsController@newEdit');

由于$factor变量是Factor模型的类型提示,并且变量名称与{factor} URI段匹配,因此Laravel将自动注入ID匹配请求URI中的相应值。