Serving Uploaded Images With Laravel 5

Let’s say you have a website with image upload functionality. It’s a good practice to save the uploaded files into your application’s storage directory which can be accessed via storage_path() helper method.

When uploading an image, you may need to store different resolutions of the image in each resolution’s directory. I am not going to explain in detail on how to resize your images but Intervention library handles this job very easily.

When saving your images to your storage directory, you can define file path’s like below.

$originalPath = storage_path('/images/original/file.jpg'); $thumbnailPath = storage_path('/images/thumb/file.jpg');

Since users won’t have access to your storage directory, there are 2 ways to serve these images.

Using Routes

With this method, you simply return the uploaded file’s path by querying it’s filename, in our example it is file.jpg.

Route::get('images/{filename}', function ($filename) { return Image::make(storage_path('/images/original/' .$filename))->response(); }); // for thumbnails Route::get('images/thumb/{filename}', function ($filename) { return Image::make(storage_path('/images/thumb/' .$filename))->response(); });

Symbolic Links

You can simply define a symbolic link from your storage directory to your public directory as follows.

ln -s /path/to/laravel/storage/images /path/to/laravel/public/images