How should I serve an image with Laravel?

How should I serve an image with Laravel?

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

Stefan Bogdanescu

Founder & Senior Architect

Serving Images from Non-Public Storage in Laravel

Storing user profile pictures directly inside storage/app rather than public/storage is a deliberate architectural choice aimed at keeping your web root tidy. While this separation of concerns makes sense for file organization, it introduces a critical constraint: the storage/ directory is not automatically accessible via HTTP. Browsers cannot fetch files from there without explicit configuration.

Your proposed controller action demonstrates an understanding of this limitation. By verifying file existence with File::exists() and using Image::make($profile_picture_url)->response('jpg'), you are essentially acting as a proxy server. Laravel loads the image into memory, processes it if necessary (though your example does not apply transformations), and streams it back to the client. This approach works, but it is worth scrutinizing the trade-offs between this method and serving images directly from the public directory.

The Proxy Pattern vs. Direct Serving

The core mechanism in your code relies on Image::make() to read the file stream and then returning a response. This creates a memory footprint proportional to the image size. If a user uploads a high-resolution photograph, say 5MB, that entire buffer resides in PHP's memory until the request completes. While modern servers often have ample RAM, serving hundreds of such images simultaneously could trigger memory_limit exhaustion or cause garbage collection overhead during peak traffic.

Directly linking to public/storage/profile_pictures/{id}/profile_40.jpg avoids this overhead entirely. The web server (Nginx or Apache) handles the static file delivery, offloading the request from PHP-FPM or your application server. This is generally superior for performance and scalability. However, if you strictly require keeping public/ free of user-generated content, the proxy pattern remains a valid solution provided you manage memory carefully.

Implementation Considerations

When implementing the proxy approach, consider leveraging Laravel's caching capabilities to avoid reading the file from disk repeatedly if you need to apply transformations like resizing. However, your current implementation returns a fresh image instance every request. If you ever decide to add on-the-fly resizing, the Image::make() call becomes expensive because it re-decodes the raw JPEG data for every single hit.

A more robust implementation might involve checking if a cached version of the resized image exists in storage/cache. If not, generate it and store it there before serving via the proxy. This decouples the heavy lifting from the request lifecycle.

use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

public function profilePicture($person, $size = 40)
{
    $basePath = 'profile_pictures/'.$person['id'];
    $originalPath = storage_path($basePath.'/'.$person['id'].'_original.jpg');
    
    if (!File::exists($originalPath)) {
        abort(404);
    }

    // Check cache for the specific size before processing
    $cachePath = storage_path('cache/images/'.$size.'.jpg');
    
    if (Storage::disk('local')->exists($cachePath)) {
        return Storage::disk('local')->response($cachePath, ['Content-Type' => 'image/jpeg']);
    }

    // Process and cache only once
    $image = Image::make($originalPath)->resize($size, null, function ($options) {
        $options->upsize(); // Prevent shrinking if image is smaller than requested size
    });

    $image->save($cachePath);

    return Storage::disk('local')->response($cachePath, ['Content-Type' => 'image/jpeg']);
}

Security and Configuration

Regardless of where you store the files, security remains paramount. If you proceed with serving from storage/app via a controller, ensure that file paths are strictly validated against the expected directory structure to prevent path traversal attacks. The $person['id'] parameter should ideally be an integer or a sanitized string to ensure it only constructs valid subdirectories.

Furthermore, if you eventually move to direct serving from public, remember to configure your web server to serve files with the correct MIME types. Laravel's default setup usually handles this well for standard image extensions, but custom file uploads might require explicit MIME type declarations in .htaccess or nginx.conf.

Conclusion on Best Practices

There is no one-size-fits-all answer, but the decision often hinges on your specific architecture. If you prioritize performance and want to leverage your web server's static file serving capabilities for media, direct access from public/storage is generally preferred. The proxy method serves well when strict separation of concerns is mandated or when dynamic transformation is required at every request without complex caching strategies.

Your current implementation is functional but should be monitored for memory usage under load. As your application scales, consider introducing a dedicated image processing service or CDN to handle the heavy lifting of serving static assets, ensuring your application server remains focused on logic rather than I/O bound image streaming.

Our network