Download Files in Laravel
How do you download a file in Laravel? It's very simple, although there are actually a couple of ways to do it.
If it's from the public folder, we have one configuration; if it's from a disk, it's another configuration, which is the one you're seeing on the screen.
In both cases, we use the download() method, which indicates the path of the file to be downloaded.
Download from public folder
If the file is in public, you can simply return the path to that file and let the browser handle everything.
This case is the simplest, since the public folder is the only one directly accessible from the browser:
public function download($file_name) {
$file_path = public_path('files/'.$file_name);
return response()->download($file_path);
}
Download from a protected disk
In this example, I'm using a disk because it's a protected resource.
Remember that all folders outside of the public folder are private, making them ideal for storing files that we don't want to give direct access to, but rather controlled access.
Note: the disk is local, although you could also use Amazon or other providers:
config\filesystems.php
'files_disk' => [
'driver' => 'local',
'root' => app()->storagePath()
],
The path, again, is local, and to organize them I use a root path, where I save all the books that, based on some logic (for example, when you buy them), are the ones I allow to be downloaded.
El proceso es sencillo:
Storage::disk('files_disk')->download($routefile);
Storage::disk('files_disk')->download('book/' . $file->file, $name . "." . $file->type);
I agree to receive announcements of interest about this Blog.
We will see how we can download files in Laravel from the public folder and from disk.