【问题标题】:Laravel unique validation issueLaravel 独特的验证问题
【发布时间】:2014-10-26 01:40:43
【问题描述】:

我尝试对我的网站设置进行唯一验证,但这不起作用:

在我的控制器中:

$rules = array(
    'username' => 'required|unique:User,username,10',
    'email'    => 'required|email|unique:User,email,10',
    'language' => 'required|in:fr,en',
);

我的模特:

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;
    protected $primaryKey = 'id_user';
    protected $table = 'user';

}

问题是:

我的验证器Validator::make(Input::all(), $rules, $messages); 失败,它说这个用户名和电子邮件已经存在。

【问题讨论】:

  • 什么不起作用?
  • 我的验证器Validator::make(Input::all(), $rules, $messages); 失败,它说这个用户名和电子邮件已经存在。
  • usernameemail 在 DB 中是否定义为唯一的?最后一个参数 '10' 你会忽略 id_user 10。这是你想要的吗?

标签: php validation laravel unique eloquent


【解决方案1】:

Laravel 没有在自定义列中进行搜索。

所以我安装了这个插件https://github.com/felixkiss/uniquewith-validator,他做得很好:

$rules = array(
    'username' => 'required|alpha_dash|unique_with:user,username,10 = id_user',
    'email'    => 'required|email|unique_with:user,email,10 = id_user',
    'language' => 'required|in:fr,en',
);

【讨论】:

  • 是的,这就是我想要的,但我忘记在我的数据库中设置 usernameemail 唯一...
【解决方案2】:

不同意对您自己问题的回答:

“Laravel 没有在自定义列中进行搜索”。

这不是真的。

准确地说:使用插件没什么不好...


查看迁移文件的重要部分(app/database/migrations):

   // creates a DB-table named 'users'
    Schema::create('users', function (Blueprint $t) {
        $t->increments('id');
        $t->timestamps();
        // ... Here a unique field
        $t->string('user_email_one', 255)->unique();
        // ...
    });

以及UserController中的相关验证规则:

     $rules = array(
        'user_email_one' => 'required|email|unique:users',
        // ...
     );

Laravel 正在做它的工作。


使用unique:,您必须调用数据库表名,而不是模型名。

顺便说一句:你选择的插件是这样做的......

The Laravel docs about validation:

unique:table,column,except,idColumn

验证中的字段在给定的数据库表中必须是唯一的。

如果未指定列选项,将使用字段名称。


正如有关命名 mySQL 表 'User''user''users' 的有趣信息,这可能会导致您的错误。访问这个问题:

Is there a naming convention for MySQL?StackOverflowNewbie 提问,由Tom Mac 回答(最高投票和接受的答案)

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 2018-07-20
    • 1970-01-01
    • 2018-06-03
    • 2019-02-07
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    相关资源
    最近更新 更多