To create a route that handles file downloads in Laravel, you can follow these steps:
routes/web.php
file or in a specific route file:Route::get('download/{file}', 'DownloadController@download')->name('download.file');
php artisan make:controller DownloadController
DownloadController
, add a download
method that will handle the file download:<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
class DownloadController extends Controller
{
public function download($file)
{
$filePath = storage_path('app/public/' . $file);
if (file_exists($filePath)) {
return response()->download($filePath);
}
abort(404, 'File not found.');
}
}
Make sure the file you want to download is stored in the storage/app/public
directory. Alternatively, you can modify the $filePath
variable in the download
method to match your file storage location.
To protect the file downloads, you can add authorization middleware to the download
method or the route itself.
You can now use the route
helper function in your views or controllers to generate the download URL:
<a href="{{ route('download.file', ['file' => 'example.pdf']) }}">Download</a>
Make sure to replace 'example.pdf'
with the actual file name you want to download.
Now, when a user clicks on the download link, it will trigger the download
method and initiate the file download.