Laravel 8: How to Display and Download Files

This article is related to my previous article on uploading files with Dropzone. This article will therefore assume you have the migration files, controllers and models discussed in that article. Today we’ll take a look at how to set your website up so that files can be downloaded. Let’s do this!!!

Case Scenario

files/A0wjnHie4xlNR1o6qxHihU259yblArpIToGIEps8.png

The path was generated with this line:

$request->file('file')->store('files');

For more information, view the previous article. Here are a few steps you can follow to setup downloads on your website:

1. Update your routes

//Route for viewing a list of student names and links to download their imageRoute::get('view-students', [StudentController::class, 'viewFiles'])->name('student.view_files');//Route for downloading a file using the id of the related studentRoute::get('download/{id}', [StudentController::class, 'downloadFile'])->name('student.download');

2. Create and update your view.

Add the following code to your file:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>View Students</title></head><body><table>@foreach ($students as $student)<tr><td>{{$student->name}}</td><td><a href="{{ route('student.download', $student->id) }}">download</a></td></tr>@endforeach</table></body></html>

3. Update your Controller

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Models\Student;use Illuminate\Support\Facades\Storage;class StudentController extends Controller{  public function create(){   return view('students');  }public function viewFiles(Request $request){  $students = Student::all();  return view('view_students', ['students' => $students]);}public function downloadFile($id){  $path = Student::where("id", $id)->value("file_path");  return Storage::download($path);}}

Don’t forget to add the following line; you need it in order to use Storage::download().

use Illuminate\Support\Facades\Storage;

4. You’re done !!!

http://localhost:8000/view-students

Related Articles

Laravel 8: MySQL Database Query Tip Sheet #4