Laravel validation: validate field only if another is present - php

I wanted to validate an 'account_id' only if 'needs_login' is present. I did this:
$rules = [
'account_id' => ['required_with:needs_login','custom_validation']
];
But it doesn't work, because if needs_login field is not present but account_id has some value, then it tries to do the 'custom_validation'.
I also tried to put the 'sometimes' parameter
$rules = [
'account_id' => ['required_with:needs_login', 'sometimes', 'custom_validation']
];
but it didn't work.
Any ideas?
P.S.: Remember that I wanted to validate the account_id only if needs_login is present, not to check if account_id is present if needs_login does.

Have you tried required_if?
$rules = [
'account_id' => ['required_if:needs_login,1']
];

Something like this works for Laravel 5 if you are going the 'sometimes' route. Perhaps you can adapt for L4? Looks like it's the same in the Docs.
$validation = Validator::make($formData, [
'some_form_item' => 'rule_1|rule_2'
]
$validation->sometimes('account_id', 'required', function($input){
return $input->needs_login == true;
});

Related

Laravel Rules Unique if

I have some hard times with Laravel Rules (importing csv file).
I'm trying to use the Rule::unique function but when another field is not empty, for example:
public function rules(): array
{
return [
'code' => ['required', 'string', Rule::unique('product_gift_cards', 'code')],
'pin' => ['nullable'],
'sequence_number' => ['nullable']
];
}
So this code, should be unique only when sequence_number is not filled. When sequence_number is filled with something, the code should not be unique. I have deleted the unique index in the database, so it will work if I write is as needed, any suggestions?
These are the validation rules in Laravel: https://laravel.com/docs/9.x/validation#available-validation-rules
Sadly there's no unique_if rule here.
One possible solution here is you have to validate it manually. You check if the input has file uploaded using $this->hasFile('sequence_number').
$code_rules = ['required', 'string'];
// Check if sequence_number is NOT uploaded
if (! $this->hasFile('sequence_number')) {
$code_rules[] = Rule::unique('product_gift_cards', 'code');
}
return [
'code' => $code_rules,
'pin' => ['nullable'],
'sequence_number' => ['nullable']
];

Laravel validate array and exclude on specific array value

I have an array of values that I send together with other fields in a form to laravel.
The array contains a role_id field and a status field, the status can be I (Insert) U (update) D (Delete). When I validate the values in the array I want it to skip the ones where the status equals D. Otherwise I want it to validate.
private function checkValuesUpdate($userid = null)
{
return Request::validate(
[
'displayname' => 'required',
'username' => 'required',
'email' => ['nullable', 'unique:contacts,email' . (is_null($userid ) ? '' : (',' . $userid ))],
'roles.*.role_id' => ['exclude_if:roles.*.status,D', 'required']
]
);
}
I can't seem to get it to work. I've been searching all over the place for functional code as well as the Laravel documentation. But no luck so far. Has anybody ever done this?
Your problem comes from a misunderstanding of the exclude_if rule. It doesn't exclude the value from validation, it only excludes the value from the returned data. So it would not be included if you ran request()->validated() to get the validated input values.
According to the documentation, you can use validation rules with array/star notation so using the required_unless rule might be a better approach. (Note there's also more concise code to replace the old unique rule, and I've added a rule to check contents of the role status.)
$rules = [
'displayname' => 'required',
'username' => 'required',
'email' => [
'nullable',
Rule::unique("contacts")->ignore($userid ?? 0)
],
'roles' => 'array',
'roles.*.status' => 'in:I,U,D',
'roles.*.role_id' => ['required_unless:roles.*.status,D']
];

Check if name already exist in database but Id is not same in Laravel 6

Properties Table
id
name
1
abc
2
xyz
I want to check if the name exists during edit but if it is the same Property then ignore it.
When I want to insert using this code
$ruls = [
'property_type' => 'required',
'project_name' => 'required|unique:properties,name',
];
$request->validate($ruls, []);
and I want to using same validation when property edit like
select name from properties where name = name and id != 1
Please help me to solve this issue.
In your validation, you can define a rule to check name unique with id like this
$ruls = [
'property_type' => 'required',
'project_name' => 'required|unique:properties,name'.$id.',id',
];
$request->validate($ruls, []);
Ignore the current ID in question when updating:
$ruls = [
...
'project_name' => [required, Rule::unique('properties', 'name')
->ignore($id)],
];
$request->validate($ruls, []);
You can use the unique rule with ignore the id. Something like this:
$rules = [
'property_type' => 'required',
'property_name' => [
'required',
Rule::unique('properties', 'name')->ignore($property->id),
],
]
https://laravel.com/docs/9.x/validation#rule-unique

Laravel validation rules - optional, but validated if present

I'm trying to create a user update validation through form, where I pass, for example 'password'=>NULL, or 'password'=>'newone';
I'm trying to make it validate ONLY if it's passed as not null, and nothing, not even 'sometimes' works :/
I'm trying to validate as :
Validator::make(
['test' => null],
['test' => 'sometimes|required|min:6']
)->validate();
But it fails to validate.
Perhaps you were looking for 'nullable'?
'test'=> 'nullable|min:6'
Though the question is a bit old, this is how you should do it. You dont need to struggle so hard, with so much code, on something this simple.
You need to have both nullable and sometimes on the validation rule, like:
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'sometimes|nullable|between:8,20'
]);
The above will validate only if the field has some value, and ignore if there is none, or if it passes null. This works well.
Do not pass 'required' on validator
Validate like below
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'between:8,20'
]);
The above validator will accept password only if they are present but should be between 8 and 20
This is what I did in my use case
case 'update':
$rules = [
'protocol_id' => 'required',
'name' => 'required|max:30|unique:tenant.trackers'.',name,' . $id,
'ip'=>'required',
'imei' => 'max:30|unique:tenant.trackers'.',imei,' . $id,
'simcard_no' => 'between:8,15|unique:tenant.trackers'.',simcard_no,' . $id,
'data_retention_period'=>'required|integer'
];
break;
Here the tracker may or may not have sim card number , if present it will be 8 to 15 characters wrong
Update
if you still want to pass hardcoded 'NULL' value then add the
following in validator
$str='NULL';
$rules = [
password => 'required|not_in:'.$str,
];
I think you are looking for filled.
https://laravel.com/docs/5.4/validation#rule-filled
The relevant validation rules are:
required
sometimes
nullable
All have their uses and they can be checked here:
https://laravel.com/docs/5.8/validation#rule-required
if you want validation to always apply
https://laravel.com/docs/5.8/validation#conditionally-adding-rules
if you want to apply validation rules sometimes
https://laravel.com/docs/5.8/validation#a-note-on-optional-fields
if you want your attribute to allow for null as value too

Laravel 5.2 validator: Validate Array request parameter, at least one value must be selected

I am having a form where i am having title, body, answers[][answer] and options[][option].
I want atleast one answer must be selected for the given question, for example:
i have ABC question and having 5 options for that question,now atleast one answer must be checked or all for given question.
Efforts
protected $rules = [
'title' => 'required|unique:contents|max:255',
'body' => 'required|min:10',
'type' => 'required',
'belongsto' => 'sometimes|required',
'options.*.option' => 'required|max:100',
'answers.*.answer' => 'required',
];
But this is not working. i want atleast one answer must be selected.
Please help me.
The problem is that on $_POST an array filled with empty strings will be passed if no answer is selected.
$answers[0][0] = ''
$answers[0][1] = ''
$answers[0][2] = ''
Hence the following will not work since array count will be greater than zero due to the empty strings:
$validator = Validator::make($request->all(), [
'answers.*' => 'required'
]);
The easiest way to solve this is to create a custom Validator rule by using Laravel's Validator::extend function.
Validator::extendImplicit('arrayRequireMin', function($attribute, $values, $parameters)
{
$countFilled = count(array_filter($values));
return ($countFilled >= $parameters[0]);
});
And then call it in your Validation request:
$validator = Validator::make($request->all(), [
'answers.*' => 'arrayRequireMin:1'
]);
The magic happens in array_filter() which removes all empty attributes from the array. Now you can set any minimum number of answers required.
Validator::extendImplicit() vs Validator::extend()
For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an "implicit" extension, use the Validator::extendImplicit() method:
Laravel's validation docs
Try this,
'answer.0' => 'required'
it will help you. I think.

Categories