【问题标题】:Laravel validate unique if id is the same如果 id 相同,Laravel 验证唯一性
【发布时间】:2016-08-03 03:26:21
【问题描述】:

我有一个表/模型,每个用户包含多个专辑。 有没有办法说title 列应该是唯一的,但仅适用于具有相同user_id 的行?

示例:http://pastebin.com/8dvM4a1T

正如您在示例中看到的,ID 为 2 的用户创建了 2 个具有相同标题的相册。我不希望这种情况被允许,这就是为什么我想知道是否有办法通过 Laravel 的验证器来否认这一点?

我试过了,但是没有用。

// Validator
    $validator = Validator::make($input, [
        'title' => 'required|min:1|max:255|unique:galleries,title,'. Auth::user() -> id .',user_id',
        'description' => 'min:1|max:255'
    ]);

任何帮助表示赞赏,谢谢。

【问题讨论】:

  • 你使用的是什么 Laravel 版本?
  • 我目前使用的是 5.2

标签: php mysql validation laravel


【解决方案1】:

你的代码应该是这样的:

'title' => 'unique:galleries,title,NULL,id,user_id,'.Auth::user() -> id.'',

或者,您可以编写自定义规则 Reference here

【讨论】:

  • 所以这在创建中可以正常工作,但是我们应该如何自定义更新功能呢?
【解决方案2】:

使用默认 unique 规则的方法不起作用,因为该规则希望将列值作为第三个参数传递,因此在您的情况下,它将检查 title 列是否等于 Auth::user()->id值不是你想要的。

您可以通过将以下代码添加到App\Providers\AppServiceProvider 类的boot 方法来创建自己的自定义验证规则:

Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
    // Get the parameters passed to the rule
    list($table, $field, $field2, $field2Value) = $parameters;

    // Check the table and return true only if there are no entries matching
    // both the first field name and the user input value as well as
    // the second field name and the second field value
    return DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});

现在您可以像这样使用unique_custom(或者您可以随意命名)规则:

$validator = Validator::make($input, [
    'title' => 'required|min:1|max:255|unique_custom:galleries,title,user_id,' . Auth::id(),
    'description' => 'min:1|max:255'
]);

规则期望参数如下:

  • 第一个参数为表名,在本例中为galleries
  • 第二个参数应该是唯一的字段名称,其值来自用户输入,在本例中为title
  • 第三个参数是要添加到查询条件的第二个字段名,在本例中为user_id
  • 第四个参数是作为第三个参数传递的字段名称的值

您也可以使用Auth::id(),因为这是Auth::user()->id 的缩写形式。


您可以在Laravel Documentation 中阅读有关自定义验证规则的更多信息。

【讨论】:

  • 啊,我明白了。也谢谢你解释。也可以像魅力一样工作。
  • 不客气。此外,使用默认的unique 规则无法做到这一点似乎是错误的。实际上,您可以传递额外的 fieldvalue 参数以用作第二个条件,正如 @VipindasKS 在 other answer 中很好指出的那样。
  • 所以这在创建中可以正常工作,但是我们应该如何自定义更新功能呢?
猜你喜欢
  • 2017-03-26
  • 2021-03-22
  • 2018-05-24
  • 2016-04-15
  • 2022-12-05
  • 2018-07-29
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多