How to validate laravel input only when data is present? - laravel

So I have a Laravel form where I'm collecting data, I use same form for creating and updating the table. Problem is that I only want the input fields to be validated when they contain data, this is my validation logic.
$validated = $request->validate([
'site_name' => 'sometimes|string',
'site_email' => 'sometimes|email',
'site_keywords' => 'sometimes|string',
'site_description' => 'sometimes|string',
'site_acronym' => 'sometimes|string|max:7',
'site_favicon' => 'sometimes|mimes:jpg,png,jpeg,svg',
'site_logo' => 'sometimes||mimes:jpg,png,jpeg,svg',
'site_currency' => 'sometimes|string',
'site_currency_symbol' => 'sometimes|string',
]);
But when the form is submitted, laravel returns an error for empty input fields, e.g it returns an error like so "The site name must be a string." for the first validation rule.
What am I doing wrong please?
EDIT
So I took the advice from #roj-vroemen and modified my code by using the nullable validation rule and it works just fine now.
Here's the new code block
$validated = $request->validate([
'site_name' => 'string|nullable|sometimes',
'site_email' => 'email|nullable|sometimes',
'site_keywords' => 'string|nullable|sometimes',
'site_description' => 'string|nullable|sometimes',
'site_acronym' => 'string|nullable|sometimes|max:7',
'site_favicon' => 'mimes:jpg,png,jpeg,svg|nullable|sometimes',
'site_logo' => 'mimes:jpg,png,jpeg,svg|nullable|sometimes',
'site_currency' => 'string|nullable|sometimes',
'site_currency_symbol' => 'string|nullable|sometimes',
]);

You'll want to use nullable in this case. sometimes basically means it only runs the validation for that field when it's present in the data.
In short:
Use nullable when you want to allow null values.
https://laravel.com/docs/8.x/validation#rule-nullable
Use sometimes if your only want to validate the field when it's present in the given input array.
https://laravel.com/docs/8.x/validation#validating-when-present
Note: you might want to make sure to filter out the empty values as the fields containing null will still be there:
$validated = array_filter($validated);

Related

Laravel validate rule

I have two datepicker input fields: from and to. To ensure that field value to is greater than field value from, I use the after validation rule. Everything is fine up until I leave the from input value null. Because I am applying the validation rule using the input value from.
How can I combine the required and after validation rules without running into this problem?
$from = $request->input('from');
$from = Carbon::createFromFormat('Y-m-d\TH:i', $from)->format('Y-m-d H:i A');
$attributes= request()->validate([
'from' => 'required|date',
'to'=> 'nullable|date|after:'.$from,
]);
Data missing error while from input value is empty.
The laravel validation rule allows you to compare a field against another field. So you can simply add: after:from
See the documentation here.
$attributes = request()->validate([
'from' => 'required|date',
'to'=> 'nullable|date|after:from',
]);

Laravel - request validation for two nullable fields requiring at least one of them to be not-null

My model has two nullable fields, but at least one of them must be not-null.
How do I setup request validation for this ?
$request->validate([
'field_1' => ['nullable'],
'field_2' => ['nullable'],
...
]);
thanks
If you have only two filed comparisons then you can use required_without:foo,bar,...
$request->validate([
'field_1' => 'required_without:field_2',
'field_2' => 'required_without:field_1'
]);
if it has more than two fields then required_without_all:foo,bar,...
$request->validate([
'field_1' => 'required_without_all:field_2,field_3',
'field_2' => 'required_without_all:field_1,field_3',
'field_3' => 'required_without_all:field_1,field_2',
]);
As per Doc
required_without:foo,bar,...
The field under validation must be present and not empty only when any
of the other specified fields are empty or not present.
required_without_all:foo,bar,...
The field under validation must be present and not empty only when all
of the other specified fields are empty or not present.
Validation

Array Validation: unique validation on multiple columns

I am trying to check unique validation on three columns employee_id,designation_id,station_id but the data are coming as an array which is making my situation unique and different from other SO questions/answers. I already checked few question like below: checks unique validation on multiple columns
But in my case, I can't get the value as they are inside an array. I also tried to implement Custom Rule or Request but in vain. For all the attempts, I am failing to get the field value such as $request->employee_id as they are inside an array for my case. May be I'm not trying it right.
Controller Code:
$this->validate($request, [
'posting.*.employee_id' => 'required,unique: // what to do here ??',
'posting.*.designation_id' => 'required',
'posting.*.station_id' => 'required',
'posting.*.from_date' => 'required|date',
]);
I am trying to validate uniqueness for both create and update (along with ignore $this->id facility) but don't know how to implement it here for array. It would be no problem if there was no array. Any help/suggestion/guide is much appreciated. Thanks in advance.
You can do this by creating a rule i.e UniquePosting so your controller code would look like
$this->validate($request, [
'posting' => ['required'],
'posting.*' => ['required', new UniquePosting()],
'posting.*.employee_id' => 'required',
'posting.*.designation_id' => 'required',
'posting.*.station_id' => 'required',
'posting.*.from_date' => 'required|date',
]);
Now inside your UniquePosting rule passes function will look like
public function passes($attribute, $value) {
$exists = Posting::where(['employee_id' => $value['employee_id'], 'designation_id' => $value['designation_id'],'station_id' => $value['station_id')->exists();
return !$exists;
}
Add any change if needed, overall that's the concept for testing uniqueness of the whole array.

How to allow empty value for Laravel numeric validation

How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'numeric',
]);
If I understood you correctly, you're looking for sometimes rule:
'bed' => 'sometimes|numeric',
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list
In Laravel 6 or 5.8, you should use nullable. But sometimes keyword doesn't work on that versions.
Use sometimes instead of required in validation rules. It checks if only there is a value. Otherwise it treats parameter as optional.
You may need nullable – sometimes and
present didn't work for me when combined with integer|min:0 on a standard text input type - the integer error was always triggered.
A Note on Optional Fields
By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.
Tested with Laravel 6.0-dev
Full list of available rules
In laravel 5.5 or versions after it, we begin to use nullable instead of sometimes.
according to laravel documentation 8 you must to set nullable rule
for example:
$validated = $request->validate([
'firstName' => ['required','max:255'],
'lastName' => ['required','max:255'],
'branches' => ['required'],
'services' => ['required' , 'json'],
'contract' => ['required' , 'max:255'],
'FixSalary' => ['nullable','numeric' , 'max:90000000'],
'Percent' => ['nullable','numeric' , 'max:100'],
]);
in your case :
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'nullable|numeric',
]);

Laravel 5.2 - validate value in array

I am trying to ensure a field is valid if the value appears in a predefined array, but it's not working for me.
The validation rule I am using is:
'title' => [
'required',
'in' => ['Mr', 'Mrs', 'Miss', 'Ms'],
],
But it seems to pass validation if I enter an invalid value, such as "Dr".
Anyone know the correct way to do this?
Try with a string validation rule instead of array:
'title' => 'required|in:Mr,Mrs,Miss,Ms';

Resources