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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?