Home > Software design >  Laravel 9 the field must be a file even though I said it can be nullable (validation)
Laravel 9 the field must be a file even though I said it can be nullable (validation)

Time:08-11

I have this function in a validation class:

public function rules(): array {
    return [
        // ...
        'content_image'       => 'nullable|file|mimetypes:png|max:2000',
        // ...

    ];
}

I state, that this can be null, but if it is not, it must be a file that is PNG and a max size of 2mb's

Seems straight forward enough:

The request coming in a FormData from an Api call:

content: <p>1</p>
content_image: null // => Should be allowed
live_wire_component: null
page_name: test-page
page_id: 27
order: 1

The validation sais no:

{
  "content_image": [
    "The content image must be a file.",
    "Images can only be PNG"
  ]
}

I am 900% sure this is how you allow a field to be null through validation:

From the docs

nullable

The field under validation may be null.

So why does this want an image even though I said it can be null?

CodePudding user response:

Try using the sometimes rule as @SergheiLeonenco stated in comment above https://laravel.com/docs/9.x/validation#validating-when-present also note I modified the 'mimes'

public function rules(): array {
    return [
        // ...
        'content_image'       => 'sometimes|file|mimes:png|max:2000',
        // ...

    ];
}

CodePudding user response:

in your request validation change content_image attribute to this.

'content_image'       => 'nullable|file|mime:png|max:2000',

i hope it was useful

  • Related