LoginSignup
0
0

More than 1 year has passed since last update.

LaravelでCSVダウンロードしたらYou have to supply your credentials to access this resource.と言われた。

Posted at

LaravelでSCSVファイルをダウンロードしようとしたら、ファイル内でエラーが出力されていた。

CSVダウンロードコード

web.php
Route::group(['middleware' => 'auth.very_basic'], function() {
Route::get('sample/csv_download', function () {
    $cvsList = [
        ['タイトル', '本文', '名前']
        , ['テストタイトル1', 'テスト本文1', 'テスト1']
        , ['テストタイトル2', 'テスト本文2', 'テスト2']
    ];
    $response = new StreamedResponse (function() use ($cvsList){
        $stream = fopen('php://output', 'w');

        // 文字化け回避
        stream_filter_prepend($stream,'convert.iconv.utf-8/cp932//TRANSLIT');

        // CSVデータ
        foreach($cvsList as $key => $value) {
            fputcsv($stream, $value);
        }
        fclose($stream);
    });
    $response->headers->set('Content-Type', 'text/csv');
    $response->headers->set('Content-Disposition', 'attachment; filename="sample.csv"');

    return $response;
});

});

原因

原因はBasic認証です。
Basic認証をした状態でfopen関数を使うと認証に引っかかるみたいです。

解決策

①fopenを使わない
②自分の場合は一旦このルートだけbasicの外に出しました。

以上

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