【问题标题】:laravel resource function works correct but when i use it manualy doesent worklaravel 资源功能正常工作,但是当我手动使用它时不起作用
【发布时间】:2021-02-07 06:50:57
【问题描述】:

当我在 route.php 文件中使用 laravel Route::resource 函数时,我正在使用 laravel 5,我可以在我的方法的参数中获取我的模型集合,如下所示:

     //**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

感谢您的帮助。

【问题讨论】:

    标签: laravel laravel-routing


    【解决方案1】:

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

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

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

    【讨论】:

    • get 在资源和路由正确之前。问题是我想要我选择的因素,但它返回空集合。
    • Artisan route:list command... 路线是什么样的?
    猜你喜欢
    • 2014-12-03
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2018-04-25
    • 2014-09-09
    相关资源
    最近更新 更多