【问题标题】:Unique Validation in Laravel 5.4 not working as intended for where() statementLaravel 5.4 中的唯一验证无法按 where() 语句的预期工作
【发布时间】:2021-12-22 20:53:07
【问题描述】:

在这个表格中,有3个主要参数:

"is_active" (BOOLEAN)
"position" (INT)
"id" 

这是唯一规则

'position' => [
'required_if:is_active,true|integer|min:1',
Rule::unique('tablename')->where(function($query) { $query->where('is_active', '=', 'true')->where('id', '!=', $this->id); }),
],

此规则应确保position 参数在is_active 设置为true 的数据中唯一。当前的问题是该规则已被忽略,我能够保存更新/编辑功能,即使按权利应该没有通过此验证。

id=1,位置=1,is_active=true

id=2,位置=2,is_active=true

当我将位置从 2 更改为 1 时,如上所示,它应该显示错误消息,而不是成功。但事实并非如此。

编辑:$this 属性

ParameterBag {#1862
  #parameters: array:13 [
    "is_active" => "1"
    "order" => "2"
  ]
}

注意:这是在 Laravel 5.4 中,请不要建议我升级到 Laravel 8 等。

【问题讨论】:

  • 没有where,规则是否有效?
  • 是的。我刚刚意识到“$this”变量存在问题。

标签: php laravel validation laravel-5


【解决方案1】:

我假设您使用的$this->idid,它在参数中可用。

所以,你可以通过两种方式实现

  1. 使用唯一的验证规则,例如... https://laravel.com/docs/5.4/validation#rule-unique
'position' => [
    'required_if:is_active,true|integer|min:1',
    'unique:tablename,columnname,yourIDvalue',
],
  1. 你可以在函数中使用use,像这样...
'position' => [
    'required_if:is_active,true|integer|min:1',
    Rule::unique('tablename')->where(function($query) use ($yourIDvalue) {
        $query->where('is_active', '=', 'true')->where('id', '!=', $yourIDvalue);
    }),
],

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2015-05-25
    • 2016-05-15
    • 2017-07-19
    相关资源
    最近更新 更多