How to Download Files in Laravel

In Laravel, you can easily download files and offer them to users through the application. Here's a step-by-step guide on how to download files in Laravel:


Step 1: Set Up a Route

First, you need to define a route that will handle the file download request. Open the `routes/web.php` file and add the following route:


Route::get('/download/{filename}', 'FileController@download')->name('file.download');


Step 2: Create a Controller

Next, you need to create a controller to handle the download logic. Run the following command in your terminal to generate a new controller:


php artisan make:controller FileController


This will create a new `FileController.php` file in the `app/Http/Controllers` directory.


Step 3: Implement the Download Method

Open the `FileController.php` and implement the `download` method:


<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;


class FileController extends Controller

{

    public function download($filename)

    {

        $file = storage_path('app/public/' . $filename);


        if (!Storage::exists('public/' . $filename)) {

            abort(404);

        }


        return response()->download($file);

    }

}


In this example, we're assuming that the files are stored in the `public` disk, which is usually intended for publicly accessible files. Adjust the path if you are using a different disk or storage location.


Step 4: Link to the Download Route

Finally, in your views or Blade templates, create a link that points to the download route. For example:


<a href="{{ route('file.download', ['filename' => 'example.pdf']) }}">Download File</a>


Replace 'example.pdf' with the actual filename of the file you want to download.


That's it! When users click the download link, Laravel will handle the request, and the file will be offered for download.


Remember to ensure that the file you want to download exists and is publicly accessible in the storage location specified. Also, consider adding appropriate security measures if you need to restrict access to certain files.