In this episode, we add downloading functionality for the files our users have uploaded. It turns out this is pretty straightforward, especially since we already have a Livewire component handling our uploaded files.
We start by creating a new method in our component that lets us download a file by its ID. To make sure everything's wired up correctly, we temporarily use a dd()
on the file ID when the download action is triggered from the UI. Then, we update our list of uploaded files so each one has an anchor/link that, when clicked, fires off our download method with the right file ID. We play around a bit with the link styling and make sure the browser cursor behaves, so it feels like a regular download link.
Once the click handling is set up, we move on to actually downloading the file. Since we've stored file paths in our database already, all we need is to retrieve the correct file model by ID, double-check it exists, and pass its file path to Laravel's storage download method.
With all of this in place, we try it out in the browser—click a file, and just like that, the file downloads! Super easy and secure, since we’re careful to only allow downloads for IDs that exist.