1

i have seen certain techniques to protect images like to show them only to authenticated users. one example is

how-to-protect-image-from-public-view-in-laravel

It tells us only about 1 image. what if we want to retrieve multiple private images and show them to authenticated users?. What is the most appropriate way?. we cannot generate a link to storage directory right?

Community
  • 1
  • 1
Ahmed Nawaz Khan
  • 1,451
  • 3
  • 20
  • 42

1 Answers1

3

Save the images in your storage folder which isn't publicly accessible. Then create a route to generate the image based on the parameter, which could be the image name or path. Wrap this route with the auth middleware. Display the image content with appropriate headers in the controller method for the route based on its parameters.

Edit : Check this out to give you an idea.

Sample route

Route::get('securedimage/{name}', 'SecuredImageController@show');

Sample controller method

public function show($name)
{
    // check if the image with name exists in the folder that you store them
    // If the image doesn't exist then display dummy image or return nothing
    $imagePath = storage_path('/upload/' . $name);

    return Image::make($imagePath)->response();
}

Then you can access images like so

<img src="http://example.com/securedimage/ball.jpg">
<img src="http://example.com/securedimage/topsecret.jpg">
Sandeesh
  • 11,486
  • 3
  • 31
  • 42
  • what if i want to show multiple images and not a single image – Ahmed Nawaz Khan May 20 '17 at 12:35
  • It doesn't matter how many images. When you link to the image in your html or directly, it's gonna hit your route to fetch the image and not your image resource directly. – Sandeesh May 20 '17 at 12:37
  • the link i just mentioned tells us how to make an image instance to use it inside the html file. if i have lets say 20 different protect images to display on a single page, would i have to write that last line 20 times??? please explain the whole process – Ahmed Nawaz Khan May 20 '17 at 13:00
  • @AhmedKhan updated my answer to give u an idea of what i'm talking about – Sandeesh May 20 '17 at 13:47
  • That is fantastic. Thanku so much – Ahmed Nawaz Khan May 20 '17 at 14:16
  • When i go to import a class, I get 7 different options. Would you give more specifics on your Image class? `Faker\Provider\Image;` `Nette\Utils\Image;` `Svg\Tag\Image;` `League\CommonMark\Extension\CommonMark\Node\Inline\Image;` `Dompdf\Renderer\Image;` `Dompdf\FrameReflower\Image;` `Dompdf\FrameDecorator\Image;` – wruckie Feb 07 '23 at 04:09
  • This does not appear to work in Laravel 9 – wruckie Feb 07 '23 at 04:17