How to validate unique fields with custom Request when an update is made


The small problem is testing a user's editing form, when I validate the data with a custom request, it generates problems when I have unique fields.

In my case, I have the email as a single field, when I edit and I do not want to modify the email, it sends me the sign that it is taken.

public function rules()
    return [
        'name' => 'required|string|min:3|max:60',
        'email' => 'required|email|unique:users',

The first thing that occurred to me was to modify the Request rule where it says it is unique, but this allows me to put an email that is already in the database and does not say anything, it's fine, in my database it is also restricted and does not include it, but I would like it in that case if it is advised that it is taken

The next thing that occurred to me was to do this part in the controller, but I can not verify the existence of the email inside the database, so if I do a where I get a users if the email exists or a collection empty if not, but there I am.

asked by Cidius 20.10.2016 в 15:25

3 answers


In the Laravel documentation this case is explained:


unique: table, column, except, idColumn


In case you need something more complex the idea is to use the class Rule and the method ignore:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [

or as the case may be:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')
answered by 20.10.2016 / 15:32

Remember that unique in rules method, has 3 parameters:

public function rules()
    'email' => 'required|email|unique:users,email,'.$this->route('user'),

The first parameter defines the table the second the column the third is that row must ignore (with the id of this)

In this case if you do a dump and die


At the beginning of the method, you will obtain all the parameters of the request. As you should know, within the request is the path to which you are trying to access ({user} => where {user} is the id of the user you want to modify), therefore with $ this-> route ('user') access the variable {user} written in the route.


answered by 05.10.2018 в 16:04

I do it in the following way:

'email' => 'required|unique:users,email,'.$this->route(''),

In the route method, the "" parameter is the name of the resource path (in my case, users) next to the id field of the table.

In addition, the method is useful for both inserting and updating.

If it does not work, you have a dd (this- > route ('') or whatever the user path is called plus the id and check if it is actually returning the user's id.


answered by 21.10.2016 в 10:04