How to use ‘unique’ for database columns updates in Laravel validation?

When you try to update the record it will again validate the input field. It assures that there is not a record with the same field, for example email. Learn how to update the ‘unique’ keyword rule for database columns updates in Laravel validation.

The rule will check against the records table and finds the model that is saved previously. If it has the same email as the record we are trying to update, so it returns a validation error.

To deal with this we need to update the validation rule. This lets it know that it needs to check the email is unique in the table. But, not against the model we have saved previously.

Here we add another value to the unique validation rule.

use Illuminate\Validation\Rule;

public function rules()
{
    return [
	    'title' => [
		    'required',
		    Rule::unique('records', 'email')->ignore($this->record)
	    ]
    ]; 
}

Here we tell the unique rule to ensure the email in records is unique. However, it should ignore this email (the one that is being edited). So, we can update the email with the same email as the current saved model without generating a validation error.

Since there is no variable set in the SavePostRequest class which sets $this->email. So, we have to look up the inheritance chain a couple of levels.

The SavePostRequest extends FormRequest, which extends Request that has a getter method which will return the email that is passed to the route when we call $this->email. So $this->route($key), where $key is email in this case.

The unique rule is for database columns updates in Laravel validation can also be used in another way.

public function rules()
{
    return [
	    'email' => "required|unique:records,title,{$this->record->id}"
    ]; 
}

The above rule is just an extension for the original rule to insert data. The {$this->record->id} is added to notify rule exemption for the current record. Though, this one is simple to write, the first more clearly notifies the purpose of update.

However, the first one is more understandable and preferable to use.

Leave a Comment