How to Download File/Image from URL in Laravel?

To download a file or image from a URL in Laravel, you can use the `file_get_contents()` function along with Laravel's `Storage` facade. Here's a step-by-step guide:


Step 1: Set Up a Route (Optional)

If you want to trigger the download using a URL in your application, you can set up a route in the `routes/web.php` file:


Route::get('/download-file',[ DownloadController::class,'downloadFile'])->name('file.download');


Step 2: Create a Controller

Next, create a controller that will handle the download logic. Run the following command to generate the controller:


php artisan make:controller DownloadController


Step 3: Implement the Download Method

Open the `DownloadController.php` and implement the `downloadFile` method:


<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;


class DownloadController extends Controller

{

    public function downloadFile()

    {

        $url = 'https://example.com/path/to/file.jpg'; // Replace this with the actual URL of the file/image


        $contents = file_get_contents($url);

        $filename = basename($url);


        Storage::put('public/' . $filename, $contents);


        return response()->download(storage_path('app/public/' . $filename));

    }

}


In this example, we are assuming that the downloaded files will be stored in the `public` disk, which is usually intended for publicly accessible files. Adjust the storage disk and path if you want to store the file in a different location.


Step 4: Trigger the Download (Optional)

If you set up a route in Step 1, you can now trigger the download by visiting the specified URL in your browser or through an HTTP client.


If you didn't set up a route, you can call the `downloadFile` method from any other part of your application.


Keep in mind that downloading files/images from external URLs using `file_get_contents()` can be slow and resource-intensive. If you expect to handle large files or high traffic, consider using background jobs or caching mechanisms to improve performance and avoid timeouts.


Additionally, be aware of the legal implications of downloading files from external URLs and ensure you have the appropriate permissions to use and store the content.