Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
]);

I am using Laravel 5.2

if your primary key is named 'id' table name is users_table and I want to update user_name so I do it this way

'user_name'  =>  'required|unique:users_table,user_name,'.$id

if your primary key is not named 'id' In my case my primary key is user_id and table name is users_table and I want to update user_name

so I do it this way

'user_name' => 'required|unique:users_table,user_name,'.$id.',user_id'

Include Rule by writing

use Illuminate\Validation\Rule;

and write your validation code as follows:

 'Email' => [required,
            Rule::unique('driver_details')->ignore($id),
            ]

Here $id is the id of the email that you want to ignore during validation which is obtained from the controller.


Try this

'email' => 'unique:table_name,column_name,'.$this->id.',id'

$this->id will be the value from your request