LoginSignup
5
9

More than 5 years have passed since last update.

Laravelで認証済の人だけが閲覧可能なPDF出力

Posted at

認証がいらないならpublicにおけばよいが、必要な場合はstorage/app/pdf/なんかに置いたりして、認証チェックしてから出力したい。

Controller

app/Http/Controllers/PdfController.php
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class PdfController extends Controller
{
  protected static $pdfPath = 'pdf/';

  public function __construct()
  {
    $this->middleware('auth');
  }

  public function show($fileName)
  {
    $filePath = self::$pdfPath . $fileName;

    abort_if(!Storage::exists($filePath), 404);

    return response()->make(Storage::get($filePath), 200, [
      'Content-Type'        => 'application/pdf',
      'Content-Disposition' => 'inline; filename="' . $fileName . '"'
    ]);
  }
}

Routing

routes/web.php
Route::get('pdf/{fileName}', 'PdfController@show')->name('pdf.show');

View

<a href="{{ route('pdf.show', ['fileName' => 'hoge.pdf']) }}" target="_blank">PDF</a>

5
9
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
5
9