【问题标题】:Laravel Validation Rule - At least one input value change must be madeLaravel 验证规则 - 必须至少更改一个输入值
【发布时间】:2019-01-04 23:32:03
【问题描述】:

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

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

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

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

    ];

}

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

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案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() 函数,该函数将只检查该特定列的值。

    【讨论】:

    • 谢谢 Giorgi - 这可能很有用 - 现在只是对它进行一些试验和错误,但我所做的似乎不像“laravel 方式”而且非常冗长。希望有原生解决方案
    • 然后使用 isDirty() ,这是 laravel 的方式,非常灵活。阅读更多 。但基本上我发布的答案可能就是你所需要的。
    • 谢谢 - 我正在尝试将其用作验证规则功能的一部分。因此,检索现有模型,将其与数据进行比较,一切正常,但如果它是脏的,如何将其作为损坏的验证规则返回。有什么想法吗?
    • @FriendlyCode 关于您的问题。验证规则旨在确保给定数据符合我们的规范。在这种情况下这是一个逻辑验证(业务),所以我认为这个逻辑应该放在控制器中,或者更好的是,在通过验证后放在中间件中。
    • 我同意@HCK。使用我的解决方案并将其放入中间件或控制器中。您要问的不是 laravel 作为规则提供的验证逻辑。
    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2020-03-31
    相关资源
    最近更新 更多