How do I display Image from Storage Folder in Laravel

Published January 13, 2022


Programmers nowadays opt to store their images and other critical files in storage folders rather than on the web address for security reasons. Laravel has included the storage folder file upload as a precautionary measure. Unfortunately, after uploading files to the storage folder, you will have to display these files on your webpage. Unfortunately, after uploading files to a storage folder, you will have to display these files on your webpage. 

In this article, we'll look at how to display an image from the storage folder.

 

How to display an image from a storage folder in Laravel

There are two methods that you can use to display an image from the storage folder in Laravel:

·         Display image files using the asset function

·         Creating a route to display the image

 

a)    Display image files using the asset function

Using the asset function method, you may display an image by simply following the steps below:

·         Step 1: First, you need to connect your storage folder using the following command:

PHP artisan storage: link

  Step 2: Now display your image on your blade file using the asset function as illustrated in the following syntax:

<img src="{{ asset(.'/images/'.$article->image) }}" alt="" title="">

 

b)    Creating a route to display the image

In this method, we need to create a route for displaying images on our webpage. This method comprises the following simple steps:

·         Step 1: First, create  route using the following  syntax

Route::get('image/{filename}', 'HomeController@displayImage')->name('image.displayImage');

 

 Step 2: Now create a  controller method that displays the image:

public function displayImage($filename)

{

$path = storage_public('images/' . $filename);

if (!File::exists($path)) {

abort(404);

}

$file = File::get($path);

$type = File::mimeType($path);

$response = Response::make($file, 200);

$response->header("Content-Type", $type);

return $response;

}

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1372 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions