Making Laravel 8 validation rules optional to allow empty fields

1k views Asked by At

I have a Laravel 8 application. In a form I have two fields that are both optional.

I set the validation rules like so:

class ValidateAddEmptyTopic extends FormRequest {
    public function rules() {
        return [
            'title'     => 'string|max:255',
            'init_url'  => 'url'
        ];
    }
}

However it still requires the fields to be included, even without the required attribute. How can I make the fields optional while still having the validation rules applied when data is submitted from the fields?

2

There are 2 answers

0
Dilip Hirapara On BEST ANSWER

You need to add nullable validation too.

return [
        'title'     => 'nullable|string|max:255',
        'init_url'  => 'nullable|url'
    ];

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values

0
Naeem Ijaz On

Hope it will slove your problem

class ValidateAddEmptyTopic extends FormRequest {
    public function rules() {
        return [
            'title'     => 'nullable|string|max:255',
            'init_url'  => 'nullable|url'
        ];
    }
}