Home > Blockchain >  How to validate laravel input only when data is present?
How to validate laravel input only when data is present?

Time:11-26

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',
        ]);

CodePudding user response:

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