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 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试