Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I validate unique fields in a Laravel CRUD application


How do I validate unique fields in a Laravel CRUD application


To validate unique fields in a Laravel CRUD application, you can use the `unique` rule in your validation rules. Here's an example:

1. Validate Unique Field on Create:
- In your `PostController@store` method, add the `unique` rule to the validation rules:

php
     public function store(Request $request)
     {
         $validatedData = $request->validate([
             'title' => 'required|unique:posts,title',
             'content' => 'required',
         ]);

         $post = Post::create($validatedData);

         return redirect()->route('posts.show', $post->id)
                          ->with('success', 'Post created successfully.');
     }
     

- The `unique:posts,title` rule checks if the `title` field is unique in the `posts` table.

2. Validate Unique Field on Update:
- In your `PostController@update` method, you need to exclude the current record from the unique validation:

php
     public function update(Request $request, Post $post)
     {
         $validatedData = $request->validate([
             'title' => 'required|unique:posts,title,' . $post->id,
             'content' => 'required',
         ]);

         $post->update($validatedData);

         return redirect()->route('posts.show', $post->id)
                          ->with('success', 'Post updated successfully.');
     }
     

- The `unique:posts,title,$post->id` rule checks if the `title` field is unique in the `posts` table, excluding the current `$post->id` record.

3. Display Validation Errors:
- In your Blade views, you can display the validation errors using the `$errors` variable, as shown in the previous example.

4. Custom Validation Rule:
- If you need more complex validation logic, you can create a custom validation rule. For example, you can create a `UniqueWithTrashed` rule that also checks for soft-deleted records:

php
     class UniqueWithTrashed extends Rule
     {
         public function __construct($table, $column, $except = null)
         {
             $this->table = $table;
             $this->column = $column;
             $this->except = $except;
         }

         public function passes($attribute, $value)
         {
             $query = DB::table($this->table)
                        ->where($this->column, $value);

             if ($this->except) {
                 $query->where('id', '!=', $this->except);
             }

             return $query->withTrashed()->count() === 0;
         }

         public function message()
         {
             return 'The :attribute has already been taken.';
         }
     }
     

- You can then use this custom rule in your validation:

php
     $validatedData = $request->validate([
         'title' => ['required', new UniqueWithTrashed('posts', 'title', $post->id)],
         'content' => 'required',
     ]);
     

By following these steps, you can easily validate unique fields in your Laravel CRUD application, ensuring data integrity and preventing duplicate records.

Citations:
[1] https://kinsta.com/blog/laravel-crud/
[2] https://tonymasek.com/blog/how-to-make-laravel-reverb-work-on-laravel-forge
[3] https://dev.to/novu/the-ultimate-guide-to-laravel-reverb-275o
[4] https://magecomp.com/blog/crud-operation-laravel-8/
[5] https://laravel.com/docs/11.x/reverb