In Laravel 11, when you're updating a resource (like a user or product) in your database, you might want to ensure that a certain field remains unique, even during updates. For example, you might want to make sure that a user’s email address isn’t duplicated, but allow it to remain the same during the update.
In this guide, I'll show you how to apply unique validation on updates in Laravel 11 easily.
How to Create Unique Validation on Update in Laravel 11
Here’s an example of how to apply unique validation during an update in Laravel 11.
use Illuminate\Http\Request;
use App\Models\User;
public function updateUser(Request $request, $id)
{
// Validate the data
$request->validate([
'email' => 'required|email|unique:users,email,' . $id, // Unique validation for the 'email' field, ignoring the current user
]);
// Find the user and update
$user = User::findOrFail($id);
$user->update([
'email' => $request->email,
// other fields you want to update
]);
return response()->json(['message' => 'User updated successfully', 'user' => $user]);
}
You can create a request class for validation in laravel.
php artisan make:request StoreUserRequest
php artisan make:request UpdateUserRequest
app/Http/Requests/StoreUserRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
'username' => 'required|min:8',
'email' => 'required|email|unique:users,email'
];
}
}
app/Http/Requests/UpdateUserRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateUserRequest extends FormRequest
{
public function authorize()
{
return false;
}
public function rules()
{
return [
'name' => 'required',
'username' => 'required|min:8',
'email' => 'required|email|unique:users,email,'.$this->user->id
];
}
}
You might also like:
In this article, we will see how to add multiple filter dropdowns in datatable. This example is almost identical to...
Jun-06-2022
Hello developers! In this article, we'll see how to change the date format in laravel 11. Here, we'll learn...
Apr-29-2024
In this article, we will see how to use image intervention in laravel 9. Here, we will learn about image intervention an...
Feb-13-2023
In this example we will see how to google autocomplete address in laravel 8. In laravel 8 google autocomplete address tu...
Aug-16-2021