How to protect image from public view in Laravel 5?

It is possible to protect images from public view in Laravel 5.x folder.

  • Create images folder under storage folder (I have chosen storage folder because it has write permission already that I can use when I upload images to it) in Laravel like storage/app/images.
  • Move the images you want to protect from public folder to the new created images folder. You could also chose other location to create images folder but not inside the public folder, but with in Laravel folder structure but still a logical location example not inside controller folder. Next you need to create a route and image controller.

Create Route

Route::get('images/users/{user_id}/{slug}', [
     'as'         => '',
     'uses'       => 'ImagesController@show',
     'middleware' => 'auth',

The route will forward all image request access to Authentication page if person is not logged in.

Create ImagesController

class ImagesController extends Controller {

    public function show($user_id, $slug)
        $storagePath = storage_path('app/images/users/' . $user_id . '/' . $slug);
        return Image::make($storagePath)->response();

You can modify your storage path and file/folder structure as you wish to fit your requirement, this is just to demonstrate how I did it and how it works.

You can also added condition to show the images only for specific members in the controller.

It is also possible to hash the file name with file name, time stamp and other variables in addition.

Addition: some asked if this method can be used as alternative to public folder upload, YES it is possible but it is not recommended practice as explained in this answer. So the same method can be also used to upload images in storage path even if you do not intend to protect them, just follow the same process but remove 'middleware' => 'auth',. That way you won’t give 777 permission in your public folder and still have a safe uploading environment. The same mentioned answer also explain how to use this method with out authentication in case some one would use it or giving alternative solution as well.

Leave a Comment