0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel5.8で404エラー時の処理を実装する

Posted at

Laravel5.8で404の例外処理を実装したので忘備録としてまとめます。

404エラー時に表示したい画面を作成

今回はviews/errors/404.blade.phpとします。

resources/views/errors/404.blade.php
<h1>404 Not Found.<br>このページは存在しません。</h1>
<p>あなたがアクセスしようとしたページは削除されたかURLが変更されています。</p>

※本来はユーザーの離脱率を下げるため、TOPページへのリンクや、サイト内検索フォームを設置する等の工夫があるのが理想です。その辺の話はこちらの記事を参考に。

Handler.phpの編集

例外処理はHandler.phpを編集することでカスタマイズ出来ます。

基本的にはこちらの記事を参考に実装していきましたが、エラーが出てしまって色々試行錯誤した結果、以下のように記述して解決しました。

app/Exceptions/Handler.php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Request;
use Response;
use Illuminate\Auth\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;  //①追加

//途中略

    public function render($request, Exception $exception)
    {
        //②ここから
        if ($exception instanceof NotFoundHttpException) { 
            return response()->view('errors.404');
        }
        //②ここまで追加
        return parent::render($request, $exception);
    }

参考記事から修正した点としては、

・①でクラスを指定する必要がある。(他にNotFoundHttpExceptionクラスが存在しているのか?原因はわかりませんが、これを記述しないとエラーが発生してしまいました。)

・②のresponse()->view('errors.404')の部分。
参考記事ではreturn view('errors.404')となっていましたが、Laravel5.8 公式ドキュメントを確認するとresponse()->view()で書けよ!と言う事だったので、公式に従って修正したら上手くいきました。

今回は404エラーの例外処理のみの解説となりましたが、他の例外処理についても調べて実装できるようになりたいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?