Laravel 7 Download File From Public Storage Folder
Laravel 24-Feb-2021

Laravel 7 Download File From Public Storage Folder

In this laravel download file from public storage folder example, you will learn how to download or display files from public storage folder in laravel apps.

Download Files From Public Storage Folder In Laravel

Follow the below steps and easily download files from public stroage folder. And as well as display files on laravel blade views:

Steps 1: Routes

First of all, you need to add the following routes on web.php file. So navigate to routes folder and open web.php file then update the following routes as follow:

Route::get('view', 'FileController@view');
Route::get('get/{filename}', 'FileController@getFile')->name('getfile');

Step 2: Create Controller File

Next, Navigate to app/controllers and create controller file named FileController.php. Then update the following methods as follow:

function getFile($filename){
    	$file=Storage::disk('public')->get($filename);
 
		return (new Response($file, 200))
              ->header('Content-Type', 'image/jpeg');
    }

The above code will download files from public storage by giving the file name and return a response with correct content type.

If you want to display files on blade views, so you can update the following methods into your controller file:

       $files = Storage::files("public");
    	$images=array();
    	foreach ($files as $key => $value) {
    		$value= str_replace("public/","",$value);
    		array_push($images,$value);
    	}
	return view('show', ['images' => $images]);

The above code gets the image files from the public storage folder and extract the name of these files and you pass them to your view.

Step 3: Create Blade View

Now, Navigate to resources\view folder. And create one blade view file named show.blade.php. Then update the following code into it:

 @foreach($images as $image)
 
  <div> 
     <img src="{{route('getfile', $image)}}"  class="img-responsive" />
  </div>
                  
 
  @endforeach

Note that, if you are getting the following errors in laravel apps, when you are working with laravel files or storage:

1: “class ‘app\http\controllers\file’ not found”.

Import File in your controller file as follow:

use File;

2: “class ‘app\http\controllers\response’ not found”.

Import Response in your controller file as follow:

use Response;

3: “class ‘app\http\controllers\storage’ not found”.

Import Storage in your controller file as follow:

use Illuminate\Support\Facades\Storage;

Conclusion

In this tutorial, you have learned how to download files from public storage folder in laravel apps with example.