Laravel验证规则-必须至少更改一个输入值

时间:2019-01-04 14:51:40

标签: php laravel laravel-5

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

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

我认为以下内容可以确保输入的标题与“ different:”中的值不同,但是我将如何仅对至少一个字段执行此操作?

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

    ];

}

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

1 个答案:

答案 0 :(得分:1)

我不知道您的解决方案,但建议您看一下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()函数,该函数将仅检查特定的列值。