LoginSignup
0
0

Laravel でCSVダウンロードと画面遷移を同時に行う方法

Last updated at Posted at 2023-10-03

結果:セッションに入れる

セッションに入れてblade側でリダイレクト。

web.php

// ダウンロードできるようにルートを書いておきます。
Route::get('/download-csv', [App\Http\Controllers\HomeController::class, 'downloadCsv'])->name('download.csv');

CsvController

use Illuminate\Support\Facades\Session;

// exportCsv()にCSV出力の処理を書いてます。
$file = $this->exportCsv($request);
// セッションに入れる
Session::flash('csv.file', $file);

HomeController

public function downloadCsv(Request $request)
{
    $file = $request->get('file');

    if ($file) {
        return response()->download(public_path($file))->deleteFileAfterSend();
    }
}

app.blade.php

// headに追加
...
<head>
    @if(Session::has('csv.file'))
        <meta http-equiv="refresh" content="0.5;url={{ route('download.csv', ['file' => Session::get('csv.file')]) }}">
    @endif
</head>

おわりに

結構苦労したのでどなたかのお役に立てると嬉しいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0