pritam1605's avatar

Image validation rule not working as expected

Here's my validation rule:

public function rules() {
        $channel_id = Auth::user()->channels->first()->id;

        return [
            'name' => 'required|max:30|unique:channel,name,' . $channel_id,
            'slug' => 'required|max:30|alpha_num|unique:channel,slug,' . $channel_id,
            'description' => 'max:1000',
            'channelImage' => 'image',

        ];
    }

    public function messages() {
        return [
            'slug.unique' => 'That  unique URL has already been taken.',
            'channelImage.image' => 'Only jpeg, jpg, png, bmp, gif and svg formats are supported.',
        ];
    }

Although, is it not mandatory to upload channel image while filling the form, the image validation rule for channelImage works as if it's mandatory i.e. I need to upload an image every time I submit the request.

Why is working like that?? I did not mention required rule for channelImage, still why it is validating channelImage when I am not uploading any image?

0 likes
2 replies
andonovn's avatar

Make sure to apply the nullable validation rule to all non-required fields.

Example: 'channelImage' => 'image', to become 'channelImage' => 'nullable|image',

JackJones's avatar

If the file is not present at all then it won't be in the request, so you should use:

'channelImage' => 'sometimes|image'

unless I'm mistaken

Please or to participate in this conversation.