如果id相同,则Laravel验证unique


Laravel validate unique if id is the same

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

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

正如您在示例中看到的,id为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'
    ]);

感谢任何帮助,谢谢。

您的代码应该类似于:

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

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

默认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文档中阅读更多关于自定义验证规则的信息。

Laravel 5.3及以上

use Illuminate'Validation'Rule;
'email' => Rule::unique('galleries')->where(function ($query) {
     $query->where('user_id', Auth::id());
 })

Laravel 9

use Illuminate'Validation'Rule;
Rule::unique('galleries')->where(fn ($query) => $query->where('user_id', Auth::id()))