Unique validation in Laravel for update request

In a previous post, I’ve written about the Power of Form Request in Laravel. This post is a small addition which is about the unique validation rule, especially on update requests.

The validation rules on the store and update requests might have a lot in common but one of the major differences is how to handle the unique validation.

In this example we have an application in which we need to provide a slug for our blog posts. Let’s start with the validation rules on the store request.

use Illuminate\Validation\Rule;

...

public function rules(): array
{
    return [
        'slug' => ['required', Rule::unique('posts', 'slug')],
    ];
}

This rules requires a slug which should be unique for the posts table and validates on the slug column.

But if we use the same rule on the update requests without changing the slug, the validation will fail. The posts is already stored and the slug is already present.

We need to change to rule to exclude the slug of the current post.

use Illuminate\Validation\Rule;

...

public function rules(): array
{
    // Retrieve the post model (as it's loaded with route model binding)
    $currentPost = $this->route('post');
    // Retrieve the post model (when not loaded with route model binding)
    //$currentPost = Posts::where('field', '=', $this->route('post'))->firstOrFail();

    return [
        'slug' => [
            'required', 
            Rule::unique('posts', 'slug')
                ->ignore($currentPost->slug, 'slug')
        ],
    ];
}

With this change the validation will perform the unique validation, but ignores the slug of the current post.

Do you have any questions or comments? Feel free to talk to me on Twitter.