Laravel’s unique validation rule ensures that a specified attribute in a database table is unique. However, sometimes you may need to apply unique validation with conditions. Laravel offers a flexible way to achieve this using custom validation rules and closures.
To demonstrate this, let’s say we have a scenario where we want to ensure that a user’s email is unique only if their account status is active. Here’s how you can implement this in Laravel 11:
- Create a Custom Validation Rule:
Start by creating a custom validation rule using theValidator
facade or by extending Laravel’sValidationRule
class. For our example, let’s create a rule namedunique_if_active
. - Implement the Rule Logic:
Define the logic inside the custom rule’spasses
method. Check if the provided attribute value is unique only when the condition is met. In our case, check if the user’s account status is active before validating uniqueness. - Usage in Validation:
Now, you can use this custom validation rule in your validation logic, specifying the attribute and conditionally applying the unique validation based on other attributes’ values.
Here’s an example implementation:
// Define the custom validation rule
Validator::extend('unique_if_active', function ($attribute, $value, $parameters, $validator) {
$table = $parameters[0];
$column = $parameters[1];
$conditionColumn = $parameters[2];
$conditionValue = $parameters[3];
return \DB::table($table)->where($column, $value)
->when($validator->getData()[$conditionColumn] == $conditionValue, function ($query) use ($attribute, $value) {
$query->where($attribute, '!=', $value);
})->count() === 0;
});
// Usage in validation rules
$validator = Validator::make($request->all(), [
'email' => [
'required',
'email',
'unique_if_active:users,email,status,active',
],
// Other validation rules...
]);
if ($validator->fails()) {
// Handle validation errors...
}
In this example:
- We create a custom validation rule named
unique_if_active
. - The rule accepts parameters such as table name, column name, condition column, and condition value.
- Inside the closure, we perform a database query to check uniqueness only when the condition (
status == active
) is met. - Finally, we use this custom rule in the validation rules array, specifying the necessary parameters.
By following these steps, you can implement unique validation with conditions in Laravel 11 effectively.