Resize image in Laravel 5.2

Resize image in Laravel 5.2

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

Stefan Bogdanescu

Founder & Senior Architect

Resizing Images in Laravel 5.2: A Practical Approach to File Handling

Your current implementation handles file validation and storage correctly, but it completely skips the resizing logic. The code you posted moves the raw file directly to the public/images/ServiceImages directory using a random filename. While this works for simple uploads, storing unoptimized or high-resolution images can bloat your application's storage and slow down page loads. To fix this, you need to introduce an image processing step between validation and moving the file.

In Laravel 5.2, the most common approach is to utilize the Intervention/image package. This library extends the PHP GD or ImageMagick extensions to provide a fluent interface for manipulating images. Without it, you would be writing verbose loops to resize pixels manually, which is error-prone and hard to maintain.

Installing the Dependency

Before touching the controller logic, ensure the processing library is available. Run the following command in your terminal:

composer require intervention/image

Once installed, Laravel will load the Intervention\Image facade automatically in most environments, but you may need to add the alias to your app/config/app.php configuration file if you are using a custom environment setup or older versions of the framework. Look for the aliases array and ensure it contains:

'Image' => 'Intervention\Image\Facades\Image',

Implementing the Resize Logic

With the dependency in place, you can modify your controller method to generate a thumbnail before saving. The goal is to keep the aspect ratio intact while forcing the width or height to a specific maximum dimension.

Here is how you update your code block:

if ($request->hasFile('image')) {
    if ($request->file('image')->isValid()) {
        $file = $request->file('image');
        $destination = base_path() . '/public/images/ServiceImages';
        
        // Ensure the destination directory exists
        if (!is_dir($destination)) {
            mkdir($destination, 0755, true);
        }

        $extension = $file->getClientOriginalExtension();
        // Generate a unique filename based on the current timestamp
        $fileName = date('Ymd_His') . '_' . rand(111, 999) . '.' . $extension;

        if (!empty($data['Image'])) {
            unlink(public_path() . '/images/ServiceImages/' . $data['Image']);
        }

        // Create the image instance from the uploaded file
        $image = Image::make($file->getRealPath());

        // Resize logic: constrain to 800px width and 600px height, maintaining aspect ratio
        $image->resize(800, 600, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize(); // Prevents blurring if original is smaller than target
        });

        // Save the processed image to the destination
        $path = $image->save($destination . '/' . $fileName);

        if ($path) {
            $service->image = $fileName;
        }
    }
}

Critical Implementation Details

There are three specific decisions in this implementation that often trip up developers.

First, always verify that the destination directory exists before attempting to move or save files. The mkdir call ensures the path is ready, using 0755 permissions which are standard for web servers but allow your application user to write. If you omit this check on a production server with restrictive file permissions, your resize operation will fail silently unless you handle the exception explicitly.

Second, look closely at the resize callback. The method aspectRatio() is crucial here. Without it, Laravel's Intervention image library would stretch or squash the original image to fit the 800x600 box exactly, distorting the visual content. By enabling aspect ratio preservation, you ensure that if a user uploads a vertical image (like a portrait), it gets cropped or padded rather than stretched horizontally.

Third, consider the upsize() flag. If a user uploads a small icon (say, 50x50 pixels) and your code forces an 800px width without upsizing, the resulting image will look pixelated. Adding $constraint->upsize() ensures that if the original image is smaller than the target dimensions, Laravel will scale it up smoothly using the available quality settings.

Storage Optimization

Finally, remember that resizing does not happen automatically on every request. The file must be processed once at upload time. If you are serving these images through a CDN or a dedicated asset manager, ensure your rewrite rules point to the ServiceImages directory correctly. Also, do not forget to run the Laravel cache:clear command after adding new dependencies or changing configuration files in a production environment to ensure the Image facade resolves correctly.

Our network