dpcnm2132
2018-04-14 15:42
浏览 62
已采纳

我应该如何验证Laravel中另一个用户正在更新的用户对象?

I have a Laravel application where a superadmin user can edit other users.

Please mind that superadmin should be able to edit user's password too. Since I can't really show the password to the people ( it is hashed anyway ) I just show an empty input field for the password. What is the best way to validate this user object?

My form looks like this:

<form class="form-horizontal" method="post" action="{{ route('update_user') }}">
    @csrf
    <input type="hidden" name="user_id" value="{{ $user->id }}">
    <input type="text" name="name" value="{{ $user->name }}">
    <input type="password" name="password" >
    <button type="submit">
</form>

My rules in FormRequest looks like this:

public function rules()
{
    $userId = $this->input('user_id');
    return [
        'name' => 'sometimes|required|string|max:255',
        'password' => 'sometimes|required|string|min:6|confirmed'
    ];
}
  • The scenario is that superadmin edits just the name field and submits the form.
  • Password is recieved as null.
  • So the password rule gives an error.

I can handle this by unsetting the password value on the request if it is null. But I sincerely believe it is a lame way to do it. Is there a better way to achieve this?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongxian5735 2018-04-16 13:18
    已采纳

    You probably want to add an “after” validation hook. This will allow you add a “sometimes” rule to validate the password only if it’s not empty:

    class UpdateUserRequest extends FormRequest
    {
        public function rules()
        {
            return [
                'name' => 'required|string|max:255',
            ];
        }
    
        public function withValidator($validator)
        {
            // If password value is not empty, add the validation rules
            $validator->sometimes('password', 'required|string|min:6|confirmed', function ($input) {
                return ! empty($input->password);
            });
        }
    }
    

    If you then only want the validated data, you can called the validated() method on your request:

    $user->update($request->validated());
    

    So if the password wasn’t validated (because it was left empty) then it won’t be present in the array returned by the validated() method.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题