Sebastian Faltoni Software Architect. Passionate about Clean Code, Tech, Web, AI, .NET, Python, IOT, Swift, SwiftUI and also Blazor

Laravel Unique Validation rule on update has already been taken

36 sec read

You got the validation rule with unique working on create, but when you are trying to update the same record your get The name has already been taken error? this is due to the fact that your validator is checking for uniqueness without taking in account that your trying to update the same record which already own that name.

Let’s suppose you have your validations rules defined as a class property like so.

protected $rules =
    [
        "name" => 'required|min:10|max:100|unique:taxonomies',
    ];

What is important for the next example to work is that the unique validator is at the end of the string, so the following will work.

public function update(Request $request, Taxonomy $taxonomy)
{
    $rules = $this->rules;
    $rules['name'] = $rules['name'].',id,'.$taxonomy->id;
    $validator = Validator::make($request->all(), $rules);
    .....
}

As you can see what I did is concat to the name rule the id of the existing record, so the validator will know that we are trying to update it self and there is no conflict.

Sebastian Faltoni Software Architect. Passionate about Clean Code, Tech, Web, AI, .NET, Python, IOT, Swift, SwiftUI and also Blazor

Laravel Livewire Property is not loaded when fill is…

If you are using Laravel Livewire, and on your component your are trying to load properties from your eloquent model using fill, for example...
Sebastian Faltoni
33 sec read

Getting started with your first Laravel 8 and Jetstream…

Requirements NodeJS last version PHP Composer Introduction I’ve been programming for more than 20 years, mostly with .NET. Recently I had to work on...
Sebastian Faltoni
7 min read

Leave a Reply

Your email address will not be published. Required fields are marked *