Norbertho's avatar

Image upload validation

Hi, I would like to validate image only if the user select an image. if the user dosent select any image then i dont want to validate the image. i am using this validation in my controller but it still gives me an error that he "images must be a file of type: jpeg, png, jpg, gif, svg." Any good solution?

        $request->validate([
            'name' => 'required',
            'images' => 'sometimes|nullable|mimes:jpeg,png,jpg,gif,svg',
        ]);
0 likes
8 replies
MichalOravec's avatar
$request->validate([
    'name' => 'required',
    'images' => 'sometimes|required|mimes:jpeg,png,jpg,gif,svg',
]);
Norbertho's avatar

Thanks for the reply @ericzwart and @michaloravec i have changed my validation as you have advised but still if i dont select an image i still geting the validation error message " The images must be a file of type: jpeg, png, jpg, gif, svg."

$request->validate([
            'name' => 'required',
            'images' => 'sometimes|required|mimes:jpeg,png,jpg,gif,svg',
        ]);

This is what i ave if I dd mar request:

array:2 [
  "name" => null
  "images" => "null"
]
MichalOravec's avatar

Propably like this, it;s almost what did you have before, just nullable is before sometimes.

$request->validate([
    'name' => 'required',
    'images' => 'nullable|sometimes|mimes:jpeg,png,jpg,gif,svg',
]);
Norbertho's avatar

This was the only way how I was able to sort this out.

        if($request->images === "null"){
            $request->validate([
                'name' => 'required',
                'visible' => 'required',
            ]); 
        }else{
            $request->validate([
                'name' => 'required',
                'visible' => 'required',
                'images' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
            ]);  
        }

Please or to participate in this conversation.