如果id相同,Laravel验证唯一

Kai*_*all 5 php mysql validation laravel

我有一个表/模型,每个用户包含多个相册.有没有办法说该列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'
    ]);
Run Code Online (Sandbox Code Playgroud)

任何帮助表示感谢,谢谢.

小智 7

你的代码应该是这样的:

'title' => 'unique:galleries,title,NULL,id,user_id,'.Auth::user() -> id.'',
Run Code Online (Sandbox Code Playgroud)

或者,您可以在此处编写自定义规则 参考


Bog*_*dan 6

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

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

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;
});
Run Code Online (Sandbox Code Playgroud)

现在你可以使用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'
]);
Run Code Online (Sandbox Code Playgroud)

规则要求参数如下:

  • 一个参数是表名,在本例中是galleries
  • 第二参数是指被认为是唯一的字段名和其值来自用户的输入,在这种情况下是title
  • 所述第三参数来是将被添加到查询条件的第二字段名称,在这种情况下是user_id
  • 第四个参数是作为第三个参数传递的域名的价值

你也可以使用,Auth::id()因为那是简短的形式Auth::user()->id.


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

  • 你非常欢迎.我似乎错误地认为使用默认的`unique`规则无法做到这一点.事实上你可以传递额外的`field`和`value`参数作为第二个条件,正如@VipindasKS在[其他答案]中非常明确地指出的那样(http://stackoverflow.com/a/36575405/351330). (2认同)