Laravel Validation of unique fields

Laravel Validation of unique fields e.g email

Basic server side validation in Laravel is ridiculously easy. The following inside a controller will validate the passed values and redirect back if it fails.

$this->validate($request, [

            'firstName' => 'required',

            'lastName' => 'required',

            'email' => 'required|unique:users',

            'password' => 'required|confirmed',

            ]);

You can see what fields are required; the email has to be unique in the database users table and the password is required and must match a field named ‘password_comfirm’. When this validation passes you can then add the new user.

What about UPDATING or (PUT/PATCH) the user form is returned, the firstName has changed and the email remains the same. The original validation code will not pass and return an error of ‘email already in use’.

Solution

$this->validate($request, [

            'firstName' => 'required',

            'lastName' => 'required',

            'email' => 'required|unique:users,email,'.$id.'',

            ]);

The email’s unique rule now looks up the users table, looks for the email address except where the id column matches $id

For more information: https://laravel.com/docs/5.4/validation#rule-unique