Download and Upload Files In Laravel

Nowadays, File upload and download functionality almost mandatory. Laravel provides simple and easy ways to upload and download files. You can store these files in public folder or local storage.

In this blog, we will see some practical examples to upload and download files in Laravel. Here, we have used Test Controller and statically defining files. You can use same methods with a form for uploading files and database or directory-based listing and selection for downloading the file.

Here, we will use Storage facade to store or upload file. Before using upload and download functionality make sure file configurations for your application. Sometimes storing files to custom location or in custom directory structure you need to configure it in filesystems.php.

Before starting, link your local storage with application using below command :

Uploading and Storing File in Laravel

In Laravel, there are many ways to store or upload file into your application even some library are also available to handle file storage. While file uploading Laravel give unique name to file but you can change it as per your requirements.

The storage facade provides many functions to store files. But put() and putFileAs() methods are commonly used. The put() function will take two parameters first one is storage name and second one is file. Let's take example to understand both functions.

Output :

Here, we can also use move() function to upload file. In this method, we simply chain move() method with request object. The move() method will take two parameters first one is folder and second one is file name.

Downloading File in Laravel

Downloading files is much easier then uploading in Laravel. The storage facade's download method is used to download file in Laravel. Here, we can also use Storage to return file as response with some header if required.

The download() method takes file path as parameter. It will automatically starts download. It's considered best practice to check file exists or not before downloading. Let's take example to download file on Laravel :

In above example, we have used two methods to download file. Storage method will take path as parameter and response method will take full file path and second parameter is file name.

Conclusion

In this article, you have learned to upload and download files using multiple methods in Laravel.


Share your thoughts

Ask anything about this examples