简体   繁体   中英

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

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?

in your request validation change content_image attribute to this.

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

i hope it was useful

Try using the sometimes rule as @SergheiLeonenco stated in comment abovehttps://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',
        // ...

    ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM