Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rchakrabarty's avatar

How to make Image Preview with Session retaining the image

I am building an image preview with session, the issue I am facing is that I am getting an error below image field "Image failed to upload"

My goal is to attain:

  1. Image preview must remain even if other form fields (like bird_name) fail validation.
  2. The image must be validated properly without throwing the error "The image failed to upload."
  3. The image should not be deleted if the other form fields fail validation.
  4. Form validation should happen after the image upload, and if the image is valid, it should be saved in the session for preview.

What needs to happen:

  1. Upload the image first and validate the image separately to ensure that it can be used for preview.
  2. Perform form validation afterward.
  3. If any field (other than the image) fails validation, the image should remain in the session so that it can be displayed for preview.
  4. If the image fails validation, it should be removed, and no preview should be shown.

This is my logic in controller

This code is working, preview is also working , image getting uploaded to temp folder as well, but error below image field "Image failed to upload" comes up.

What do I observed, if I removed this part, this error gets omitted "Image failed to upload

if ($request->hasFile('image')) {
            $file = $request->file('image');
            
            // Validate image separately for size and type
            $imageValidator = Validator::make(['image' => $file], [
                'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:500',
            ]);

            // Step 3: If the image is valid, upload it to a temporary location for preview
            if (!$imageValidator->fails()) {
                $filename = 'temp_' . bin2hex(random_bytes(10)) . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('uploads/temp'), $filename);

                // Store the filename in the session for preview
                $fileHash = md5($filename);
                $request->session()->put('pending_upload_' . $fileHash, $filename);
                $request->session()->put('pending_upload_hash', $fileHash);
            } else {
                // If the image is invalid, clear any pending image preview
                $request->session()->put('pending_upload_hash', null);
            }
        }

How to fix this?

I can't use ajax, as requirement is strictly avoid ajax to me. @Snapey @tykus @Sinnbeck please

0 likes
27 replies
Snapey's avatar

Don't tag people for their input as this puts off all the other great helpers on this site.

Where does that message come from and where do you see it?

rchakrabarty's avatar

@Snapey oh am sorry will not do it again I get the error below the input field image its a validation error I guess as I dont have such custom message for image "Image failed to upload"

Snapey's avatar

you are not using any upload javascript?

rchakrabarty's avatar

@Snapey NO just a simple file reader code for previewing image nothing to worry over there as it wont have much in it.

Snapey's avatar

try with various sizes of file

rchakrabarty's avatar

@Snapey I tried but the issue is same for all either less than 500 kb or more than that also, also my upload_max_size & post_max_size is 512M so I think nothing to worry for that too as well

rchakrabarty's avatar

I tried this as well but the result is same

Jsanwo64's avatar

@rchakrabarty

The issue you're encountering is likely due to the fact that the image validation is being performed twice: once in the separate $imageValidator and again in the main $validator. When the main $validator runs, it checks the image field again, and if it fails, it adds the error message "Image failed to upload."

To fix this, you need to ensure that the image validation is only performed once, and that the image is not re-validated if it has already been validated and uploaded to the temporary location. Here’s how you can adjust your code:

  1. Remove the image validation from the main validator: Since you are validating the image separately, you don't need to include it in the main validator.

  2. Only validate the image if it hasn't been validated and uploaded yet: Check if the image has already been uploaded and validated by checking the session.

$validator = Validator::make($request->all(), [
           'bird_name' => 'required|string|unique:birds,bird_name',
           'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:500',
           'image_alt_tag' => 'required|string|unique:birds,bird_alt_tag',
           'status' => 'required|in:1,2'
       ]);

       if ($request->hasFile('image')) {
           $file = $request->file('image');
           
           // Validate image separately for size and type
           $imageValidator = Validator::make(['image' => $file], [
               'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:500',
           ]);
rchakrabarty's avatar

@jsanwo64 If I will use this then suppose if bird_name will have error but user have uploaded the image, image will not come to the preview as bird_name has error so it will stop there and further will not let the image to get uploaded to temp folder

Jsanwo64's avatar

@rchakrabarty

more like this

rchakrabarty's avatar

@jsanwo64 This will not solve my issue as well as I need all errors to be shown at a time, like what you gave will give the error of image separate and bird_name separate

Jsanwo64's avatar

@rchakrabarty Try the suggestion i gave with a different image format or remove png from the validation rule and try uploading a png image to verify it works.

You most likely will get the error if you do then there is no need to validate twice like you did in your code

rchakrabarty's avatar

@jsanwo64 Nah its not working to my requirements ser I am getting the error of "Image failed to upload"

rchakrabarty's avatar

@jsanwo64 I have given already that store code blade javascript has nothing to do with it as its a validation error, and I haven't used anything i blade and javascript file

Jsanwo64's avatar
rchakrabarty's avatar

@jsanwo64 It wont sir it will be in the same rotation image validation will not come up with all other validations sir I have tried this as well, what will happen in this case is if image and bird_name both will have errors then only image will trigger then again you need to submit to get the bird_name error

Jsanwo64's avatar

Try this lets see @rchakrabarty

Jsanwo64's avatar

@rchakrabarty
Changes made

  1. Used File::ensureDirectoryExists() to avoid redundant checks.
  2. Ensured validation logic is clear and concise.
  3. Properly handled session cleanup for failed uploads.
  4. Used Auth::id() instead of Auth::user()->id.

Also, if there seems to be an error, you will need to show the following codes;

The form The controller and also the error returned

rchakrabarty's avatar

@jsanwo64 It will be same sir I can't show errors separately in this case if the errors in bird_name will happen then it will not wait for image it will simply redirect back with bird_name error

rchakrabarty's avatar
rchakrabarty
OP
Best Answer
Level 1

This is the logics from controller

This is from my blade

Please or to participate in this conversation.