In Laravel sometime you want to exclude some validations on specific condition. Laravel provides exclude_if, exclude_unless and sometimes validation rules to validating some rules conditionally. In this tutorial we will take a simple example of has_city
is checked then city
name should be require and if its not checked then it will not validate .
So here is the syntax of exclude_if
'exclude_if:field_name,boolean|other_validation_if_true',
Example
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data, [
'has_city'=>'required',
'city' => 'exclude_if:has_city,true|required',
]);
Complex condition validation on multiple conditions
Sometime we need to check multiple condition or some logic to add the validation thus in that case we can use sometimes
validation to add the condition validations in laravel.
In this example we will use age
and gender
, if age is greater then 18 then user must need to enter the gender and age is less then 18 then we will not validate the input
Syntax
$validator->sometimes('field_name','multiple_validations_to_apply', function ($input) {
return boolean;
});
Example
$validator->sometimes('gender','require|in:Male,Female', function ($input) {
return $input->age>18;
});
Here, we are checking if age is greater then 18 then gender is required and it must be either female or male.
We can also validate array conditionally as below
$validator->sometimes('user.*.address','require', function ($input, $item) {
return $item->address_type === 'home';
});
There is another way too which we can implement in any Laravel version. Generally we create a set of rules for validation and then validate them by passing it to Validation::make
method.
So, Here we will create a array rules and then we will add rule conditionally to this array as below
<?php
$rulesList=["name"=>"required","age"=>"required"];
if($request->checked==1){
$rulesList["city"] ="require";
}
if($request->age>18){
$rulesList["gender"] ="require|in:Male,Female";
}
$validator = Validator::make($data, $rulesList);