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

时间:2018-06-06 10:58:38

标签: php laravel laravel-5 eloquent laravel-5.2

//在验证部分“alias”字段应该是唯一的,所以我需要这个NursingHome对象id(主键)来强制验证不检查这个id。

我已使用$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);
}

1 个答案:

答案 0 :(得分:0)

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);
    }

如果您的模型有两个或更多单词,则必须使用小写字母。