Framework: Validator Error: Forcing A Unique Rule To Ignore A Given ID fails if primary key is not named "id"

Created on 6 Mar 2014  路  7Comments  路  Source: laravel/framework

To reproduce, define some validation rules that use the "unique" rule:

$rules = array(
    'username'  =>  'required|min:5|unique:users,username,123',
);

$validation = Validator::make(Input::all(),$rules);
if($validation->passes()) {
      return 'Ok.';
}

The rule fails to generate the proper query if the referenced table does not rely on a primary key named "id". E.g. if your table is defined using a primary key of "user_id", the query and validation rule fails

    Schema::create('users', function(Blueprint $table) {
        $table->increments('user_id')->unsigned();
        // ... etc...

Even if the model includes

protected $primaryKey = 'user_id';

Laravel version 4.1.23

Most helpful comment

The 'unique' rules also accept the custom primary key column name in the fourth parameter. Your rules should be edited as

$rules = array(
    'username'  =>  'required|min:5|unique:users,username,123,user_id',
);

See: https://github.com/laravel/framework/blob/master/src/Illuminate/Validation/Validator.php#L893

All 7 comments

The 'unique' rules also accept the custom primary key column name in the fourth parameter. Your rules should be edited as

$rules = array(
    'username'  =>  'required|min:5|unique:users,username,123,user_id',
);

See: https://github.com/laravel/framework/blob/master/src/Illuminate/Validation/Validator.php#L893

That needs to be in the docs: http://laravel.com/docs/validation#rule-unique

I just ran into this problem as well and had to look at the source to figure out why it wasn't working. The docs do not explain what the idColumn parameter does at all. I also think it would make sense to use the value of the second parameter (column) as the default instead of 'id'. For example, if my rule looks like this:

array(
    'number' => unique:users,number,1
);

then the database row with the value of 1 in the number column should be ignored from the unique test.

As fireproofsocks said, this "feature" of specifying the custom primary key column name as the fourth parameter of the unique rule needs to be added to the docs at http://laravel.com/docs/validation#index. Most developers would not intuitively consider this as a possibility since we're told in the docs that if we have a custom primary key field just define it in a $primaryKey class data member so Laravel becomes aware.

@letrunghieu ... Thanks.

@letrunghieu Thanks a :+1:

Sorry to bother you all, but unique:users,username,123 validation rule should by default look for $primaryKey, instead of id.

@letrunghieu thanks, that helped.

But I don't think this issue is resolved (using laravel 7), please consider reopening.

Was this page helpful?
0 / 5 - 0 ratings