Laravel ファイルダウンロード方法

Laravel

ファイルをstorageに用意

Laravel
   ┗ storage
        ┗ app
           ┗ public
               ┗ susr.xlsx

コントローラーを用意する

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class FilesController extends Controller
{
    public function download()
    {
        $filePath = 'public/susr.xlsx';
        $fileName = 'susr.xlsx';
        
        $mimeType = Storage::mimeType($filePath);
            $headers = [['Content-Type' => $mimeType,
                  'Content-Disposition' => 'attachment; filename*=UTF-8\'\''.rawurlencode($fileName)
        
        return Storage::download($filePath, $fileName, $headers);
    }
}    

Bladeファイルを用意する

<a href="{{ route('download') }}">ダウンロード</a>

route

 Route::get('/excel/download', [ExcelTargetUserController::class,'download'])->name('download'); 

コメント