首页 > 解决方案 > Laravel 验证规则 - 必须至少更改一个输入值

问题描述

我有一个带有标题、副标题、日期的模型,并且正在构建一个允许用户提交更改请求的表单。

如何验证以确保至少进行了一次编辑,将输入字段与数据库值进行比较?

我认为下面将确保输入的标题与“不同:”中的值不同,但我如何只为至少一个字段执行此操作?

public function rules()
{

    return [
        'title' => [
            'required',
            'different:Dynamic Title name here',
            'string',
            'max:60',
            'not_regex:/[\x{1F600}-\x{1F64F}]/u'
        ],
        'subtitle' => [
            'string',
            'nullable',
            'max:90',
            'not_regex:/[\x{1F600}-\x{1F64F}]/u'
        ]

    ];

}

例如,显示标题、副标题、日期字段。用户必须从当前设置的数据库值中至少编辑其中一个才能提交。

标签: phplaravellaravel-5

解决方案


我不知道您的解决方案,但我建议您看一下 isDirty() 函数。

/**
* this will return false, because after we get the record from
* database, there's no attribute of it that we changed. we just 
* print if it's dirty or not. so it tells us: "I'm clean, nobody has 
* changed my attributes at all.
*/
$role = Role::findOrFail(1);
return $role->isDirty();

/**
* lets say We fetched this role with id=1 and its status was 1. what
* this returns is still false, because even though we set the status
* attribute equal to 1, we still didn't change it. It was 1 when we
* received it from the database and it's still 1.
*/
$role = Role::findOrFail(1);
$role->status = 1;
return $role->isDirty();

/**
* now if the status was 1 in the db, and we set it to 2, it will 
* print the true.
*/
$role = Role::findOrFail(1);
$role->status = 2;
return $role->isDirty();

您还可以将参数传递给isDirty()仅检查该特定列值的函数。


推荐阅读