Laravel check for unique rule without itself in update Laravel check for unique rule without itself in update laravel laravel

Laravel check for unique rule without itself in update


This forces to ignore specific id:

'email' => 'unique:table,email_column_to_check,id_to_ignore'

replace segments table, email_column_to_check, id_to_ignore in above example

You could check it here http://laravel.com/docs/4.2/validation#rule-unique


For those using Laravel 5 and Form Requests, you may get the id of the model of the Route-Model Binding directly as a property of the Form Request as $this->name_of_the_model->id and then use it to ignore it from the unique rule.

For instance, if you wanted to have unique emails, but also allow an administrator to edit users, you could do:

Route:

Route::patch('users/{user}', 'UserController@update');

Controller:

public function update(UserRequest $request, User $user) {    // ...}

Form Request:

class UserRequest extends FormRequest{    // ...    public function rules()    {        return [            'name' => 'required|string',            'email' => [                'required',                'email',                Rule::unique('users')->ignore($this->user->id, 'id')            ],            //...        ];    }    //...}

Please note that we are ignoring the user that is being edited, which in this case could be different than the authenticated user.


$request->validate([    'email' => 'unique:table_name,email,' . $user->id]);