user3207586
user3207586

Reputation: 141

Laravel unique validation issue

I try to make a unique validation the settings of my website but this doesn't work :

In my controller :

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

My model:

class User extends Eloquent implements UserInterface, RemindableInterface {

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

}

The problem is:

My Validator Validator::make(Input::all(), $rules, $messages); fails, it says that this username and email already exist.

Upvotes: 0

Views: 2729

Answers (2)

Daniel Gasser
Daniel Gasser

Reputation: 5133

Disagree with the answer to your own question:

"Laravel is not done to search in a custom column".

This is not true.

To be precise: There is nothing bad in using a Plugin...


See the important part of a migration file (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();
        // ...
    });

And the relevant validation rules in the UserController:

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

And Laravel is doing its job.


With unique: you have to call the DB-table name, not the model name.

BTW: the plugin you've chosen does this...

The Laravel docs about validation:

unique:table,column,except,idColumn

The field under validation must be unique on a given database table.

If the column option is not specified, the field name will be used.


Just as an interesting info about naming a mySQL table 'User', 'user' or 'users', which could have caused your error. Visit this question:

Is there a naming convention for MySQL? asked by StackOverflowNewbie, answered by Tom Mac (highest vote & accepted answer)

Upvotes: 1

user3207586
user3207586

Reputation: 141

Laravel is not done to search in a custom column.

So I have installed this plugin https://github.com/felixkiss/uniquewith-validator who did the job very well:

$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',
);

Upvotes: 0

Related Questions