Home > Backend Development > PHP Tutorial > Discover File Downloads in Laravel with Storage::download

Discover File Downloads in Laravel with Storage::download

James Robert Taylor
Release: 2025-03-06 02:22:09
Original
1023 people have browsed it

Discover File Downloads in Laravel with Storage::download

The

Laravel framework's Storage::download method provides a concise API for safely handling file downloads while managing abstractions of file storage.

The following is an example of using Storage::download() in the example controller:

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    public function download($filename)
    {
        return Storage::download(
            "documents/{$filename}",
            "custom-{$filename}",
            ['Content-Type' => 'application/pdf']
        );
    }
}
Copy after login

Another more complex example, which combines the processing of authorization and non-existence of the file:

<?php namespace App\Http\Controllers;

use App\Models\Document;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class DocumentController extends Controller
{
    public function download(Request $request, Document $document)
    {
        if (!$request->user()->canDownload($document)) {
            abort(403);
        }

        if (!Storage::exists($document->path)) {
            abort(404, 'File not found');
        }

        $document->increment('download_count');

        return Storage::download(
            $document->path,
            $document->original_name,
            [
                'Content-Type' => $document->mime_type,
                'Content-Disposition' => 'attachment',
                'Cache-Control' => 'no-cache, must-revalidate'
            ]
        );
    }
}
Copy after login

All in all, Storage::download provides a safe and efficient way to service files while hiding the details of the underlying storage provider.

The above is the detailed content of Discover File Downloads in Laravel with Storage::download. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template