laravel 5.4 upload image

laravel 5.4 upload image

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why FileNotFoundException Appears When Uploading Images in Laravel 5.4

You are encountering a specific quirk in how Laravel handles file uploads when combined with random filename generation. The error Illuminate\Filesystem\FileNotFoundException is triggered not because the physical file is missing on your server, but because the logic inside your controller attempts to validate a file handle that has already been consumed or is logically invalid after you generate a new name.

In your specific case, the root cause lies in this sequence of operations:

$name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);

The move() method is designed to move the file from its temporary location to a target directory using a specific name. However, there is a subtle interaction between generating a new name and how the underlying stream handle behaves in older versions of the framework. When you call $file->getClientOriginalExtension(), you are accessing a property of the uploaded file instance. The subsequent call to move() internally checks if the file exists at the destination path it is about to create. In some configurations or specific PHP environments within Laravel 5.4, generating a new name string before moving can confuse the internal state of the upload instance, leading the library to believe the source file is missing when it tries to stream it into the new location.

A more robust approach decouples the filename generation logic from the move operation. Instead of relying on getClientOriginalExtension() which is tied to the specific uploaded file instance state, you should handle the filename creation explicitly and ensure the directory exists before moving. Here is a corrected implementation pattern that avoids the exception:

if ($request->hasFile('input_img')) {
    $file = $request->file('input_img');

    // Validate the file first before doing anything else
    if ($file->isValid()) {
        try {
            // Generate a unique name safely
            $extension = $file->getClientOriginalExtension();
            $name = 'image_' . time() . '_' . rand(11111, 99999) . '.' . $extension;

            // Ensure the destination directory exists to prevent FileNotFoundError
            if (!file_exists(public_path('fotoupload'))) {
                mkdir(public_path('fotoupload'), 0755, true);
            }

            // Move the file using the generated name
            $file->move(public_path('fotoupload'), $name);
        } catch (\Illuminate\Filesystem\FileNotFoundException $e) {
            // Handle the specific case where the upload is truly empty or corrupted
            Log::error('File not found during move: ' . $e->getMessage());
            return back()->withErrors(['input_img' => 'The uploaded file could not be processed.']);
        } catch (\Exception $e) {
            Log::error('Upload error: ' . $e->getMessage());
            return back()->withErrors(['input_img' => 'Something went wrong while processing the image.']);
        }
    } else {
        return back()->withErrors(['input_img' => 'The uploaded file failed validation.']);
    }
}

Notice the addition of public_path('fotoupload'). Using absolute paths via public_path() is often safer than relative paths like "fotoupload" in modern Laravel versions, although 5.4 is more lenient with relative paths. The critical fix here is ensuring the directory exists before attempting the move operation. If the directory does not exist or permissions are restricted, the internal check within move() might fail, mimicking a file not found error.

Another potential pitfall in your view code is the lack of CSRF protection enforcement in the logic flow, though you have included {{ csrf_field() }}. Ensure that your route definition actually matches the action specified in the form: admin/post/insert. If the route returns a 405 Method Not Allowed or redirects unexpectedly, the request object might not be fully populated when the controller method executes, leading to confusing exceptions.

Finally, always consider the trade-off between generating random names and maintaining file integrity. While random names prevent collisions, they make debugging harder if you need to retrieve files later. If your application requires retrieving images by their original upload context, consider storing a mapping of original names to unique identifiers in your database alongside the new filename. This pattern scales better as your media library grows beyond a simple local disk storage setup.

Our network