【问题标题】:How should I validate a user object being updated by another user in Laravel?我应该如何验证 Laravel 中另一个用户正在更新的用户对象?
【发布时间】:2018-09-24 18:29:59
【问题描述】:

我有一个 Laravel 应用程序,超级管理员用户可以在其中编辑其他用户。

请注意,超级管理员也应该能够编辑用户的密码。 因为我不能真正向人们显示密码(无论如何它都是散列的),所以我只显示一个空的密码输入字段。验证此用户对象的最佳方法是什么?

我的表单如下所示:

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

我在 FormRequest 中的规则如下所示:

public function rules()
{
    $userId = $this->input('user_id');
    return [
        'name' => 'sometimes|required|string|max:255',
        'password' => 'sometimes|required|string|min:6|confirmed'
    ];
}
  • 场景是超级管理员只编辑名称字段并提交表单。
  • 收到的密码为空。
  • 所以密码规则出错了。

如果它是null,我可以通过取消设置请求中的密码值来处理这个问题。但我真诚地认为这是一种蹩脚的方式。有没有更好的方法来实现这一点?

【问题讨论】:

  • 您不需要用旧密码确认用户凭据吗?
  • 不,我不需要它。这是一个封闭的系统,他们的老板会为工人分配一个密码。当他们忘记时;老板再分配。这是一个设计不佳的流程,但我对此无话可说。
  • @SühaBoncukçu 我添加了一个我认为更准确地实现了您想要的答案:stackoverflow.com/a/49858314/102205

标签: php forms laravel request laravel-5.6


【解决方案1】:

您可能想要添加“after” validation hook。这将允许您添加“有时”规则以仅在密码不为空时验证密码:

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

如果您只想要经过验证的数据,您可以根据您的请求调用validated() 方法:

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

因此,如果密码未通过验证(因为它为空),则它不会出现在 validated() 方法返回的数组中。

【讨论】:

  • 这实际上看起来比我目前的解决方案要好得多。还要感谢关于“withValidator”方法的解释比文档更好。
【解决方案2】:

试试这个..

public function rules()
{
    $userId = $this->input('user_id');
    return [
        'name'     => 'nullable|required_without_all:password,anotherfield|string|max:255',
        'password' => 'nullable|required_without_all:name,anotherfield|string|min:6|confirmed'
    ];
}

doc

关于可选字段的说明

默认情况下,Laravel 包含 TrimStrings 和 应用程序全局中的 ConvertEmptyStringsToNull 中间件 中间件堆栈。这些中间件在堆栈中由 应用\Http\内核类。因此,您通常需要标记 如果您不希望 验证器将 null 值视为无效。

doc

required_without_all:foo,bar,...

仅当所有其他指定字段都存在时才存在且不为空 不存在验证中的字段必须是

如果表单中有任何其他字段,您可以在required_without_all: 中指定其他字段。

更新

如果您有很多表单字段,并且想轻松指定required_without_all 参数。

public function rules()
{
    $userId = $this->input('user_id');
    return [

        'name'     => [
                        'nullable',
                        'required_without_all:'. $this->requiredWithout('name'),
                        'string',
                        'max:255',
                      ],
        'password' => [
                        'nullable',
                        'required_without_all:'. $this->requiredWithout('password'),
                        'string',
                        'min:6',
                        'confirmed'
                      ]
    ];
}


public function requiredWithout($currentField) {
        $requiredWithoutValue = "";

        foreach ($this->request->all() as $key => $value) {
            //excluding _token as it will be always not empty value
            if($key != '_token' && $key != $currentField) {
                $requiredWithoutValue = $vrequiredWithoutValue. $key. ",";
            }
        }

        return $requiredWithoutValue;
    }

【讨论】:

  • 我仍然需要取消设置密码值,因为它通过空值验证并尝试将密码字段设置为空,但我会接受这个作为答案。因为我找不到更好的方法。谢谢。
  • 我不想使用'required_without_all',因为那样我将不得不写很多字段名。当它为空时取消设置密码输入值仍然是我的方式。但是,是的,它解决了。
  • @SühaBoncukçu 我不是强迫你使用'required_without_all:',但我认为这是最好的方法。
【解决方案3】:

我希望这可行:

public function rules()
{
   $userId = $this->input('user_id');
   return [
       'name' => 'required_if:password,null|string|max:255',
       'password' => 'required_if:name,null|string|min:6|confirmed'
   ];
}

通过这种方式,您可以分别验证这两个字段。不接受空请求。它应该具有两个值中的任何一个。

【讨论】:

  • 抱歉,该问题仅包含表单样本。真正的形式要复杂得多。
猜你喜欢
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 2020-02-20
  • 2016-10-21
  • 2017-06-02
  • 2017-04-17
  • 2017-02-26
  • 1970-01-01
相关资源
最近更新 更多