简体   繁体   English

在使用隐式路由模型绑定时,如何获取ID,我需要在唯一验证中使用它

[英]How to get id When Using Implicit Route Model Binding, i need it in unique validation

// in the validation section "alias" field should be unique so i need this NursingHome object id(primary key) to force validation to not to check for this id. //在验证部分中的“别名”字段应该是唯一的,因此我需要此NursingHome对象ID(主键)来强制验证不检查该ID。

I have checked it with $nursinghome->getKey() method but no success. 我已经用$nursinghome->getKey()方法检查了它,但是没有成功。

public function update(Request $request, NursingHome $nursinghome)
{
 $request->validate([
   'name' => 'required|string|max:255',
   'address' => 'nullable|string',
   'alias' => 'required|string|unique:nursing_home,'.$nursinghome->id,

]);

    $data = $request->all();
    $data['updated_by'] = Auth::guard('api')->id();
    $nursinghome->update($data);

    return response()->json($nursinghome, 200);
}

There is a know issue disscussed in laravel github , that if your model has two words like NursingHome the it is not injected in controller: laravel github中讨论了一个已知的问题,即如果您的模型有两个单词,如NursingHome ,则它不会注入控制器中:

    public function update(Request $request, $id){

        $nursinghome = NursingHome::find($id); //now you will get $nursinghome->id

        $request->validate([
            'name' => 'required|string|max:255',
            'address' => 'nullable|string',
            'alias' => 'required|string|unique:nursing_home,'.$nursinghome->id,
        ]);

        $data = $request->all();
        $data['updated_by'] = Auth::guard('api')->id();
        $nursinghome->update($data);

        return response()->json($nursinghome, 200);
    }

If your model having two or more words, you have to use only small letters. 如果您的模型有两个或多个单词,则只需使用小写字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM