How to Download File in Laravel: Simple Guide with Examples
In Laravel, you can download a file by returning
response()->download() with the file path as an argument. This method sends the file as a response to the browser, prompting the user to save or open it.Syntax
The basic syntax to download a file in Laravel uses the response()->download() method.
response(): Laravel helper to create a response.download($pathToFile, $name = null, $headers = []): Sends the file located at$pathToFileto the browser.$name: Optional. The name the downloaded file will have.$headers: Optional. Additional HTTP headers.
php
return response()->download($pathToFile, $name = null, $headers = []);
Example
This example shows how to create a route and controller method to download a file stored in the storage/app/public directory.
php
<?php use Illuminate\Support\Facades\Route; // Route in routes/web.php Route::get('/download-file', function () { $filePath = storage_path('app/public/example.pdf'); $fileName = 'downloaded-example.pdf'; return response()->download($filePath, $fileName); });
Output
Browser prompts to download 'downloaded-example.pdf' file.
Common Pitfalls
Common mistakes when downloading files in Laravel include:
- Using incorrect file paths that do not exist or are not accessible.
- Not setting correct permissions on the file or directory.
- Forgetting to use
storage_path()orpublic_path()helpers to get the full file path. - Trying to download files outside the allowed directories without proper security checks.
Always verify the file exists before returning the download response to avoid errors.
php
<?php // Wrong way: relative path without full path return response()->download('example.pdf'); // Right way: use full path helper return response()->download(storage_path('app/public/example.pdf'));
Quick Reference
Summary tips for downloading files in Laravel:
- Use
response()->download()with full file path. - Use
storage_path()orpublic_path()to get absolute paths. - Optionally specify a custom file name for the download.
- Check file existence before sending to avoid errors.
- Set proper file permissions for accessibility.
Key Takeaways
Use response()->download() with the full file path to trigger file downloads in Laravel.
Always use storage_path() or public_path() helpers to get the correct absolute file path.
Check if the file exists before returning the download response to prevent errors.
You can specify a custom file name and HTTP headers in the download method.
Ensure proper file permissions so Laravel can access the file to download.