How to edit a unique field in Laravel validation?

Unique values are required for many table columns in application development. We need to ensure that a field is unique in the database to avoid adding the same item twice. For example, the heading of an article. Moreover, we should be more careful when we edit a unique field. Validation rules should be modified for such cases. Laravel provides many handy tools for this. One such is the Unique validation rule.

When we know that there is a field that should be unique, we can assign it the unique function during database migrations.

$table->string('heading')->unique();

This generates an index in the database. It prevents two rows in the table to have the same heading when saving a record.

When we want to update the post. It checks against the article table and finds the current saved record that has the same heading as the article we are trying to update. Therefore it returns a validation error to edit a unique field.

We need to update validation rules for such cases. To make it check that the heading is unique in the table, except against the model that is in records.

We can add another value to add to the unique validation rule as shown below.

Laravel Validation rule to edit a unique field

public function rules()
{
    return [
	    'heading' => "required|unique:articles,heading,{$this->article->id}"
    ]; 
}

This sets the rule for the heading in the articles table to be unique, except for the heading we are editing.

We do this to tell the unique rule to ensure the heading in the articles table is unique but ignore this article so we can update the article with the same heading as the current saved model without getting a validation error.

We can use this rule with the Illuminate class also, as shown below.

use Illuminate\Validation\Rule;

public function rules()
{
    return [
	    'heading' => [
		    'required',
		    Rule::unique('articles', 'heading')->ignore($this->article)
	    ]
    ]; 
}

This passes the rule for all records in the articles table. However, the ->ignore functions exempt the rule for the current, i.e. article being edited.