Simplify Page Redirects with Laravel Exceptions Handler

Easily manage and redirect your pages with Laravel's Exceptions Handler. It's an efficient way to handle 404 errors, unauthorized pages, and more. This handler will wait and catch the throw 404 status then redirect the users to the not found page. This way we don't need to redirect manually every time in the controller/action, we just throw the 404 status code.

Config handler

In app/Exceptions/Handler.php

In the public function register is the code to redirect to the 404 page when getting a 404 status code

<?php

namespace App\Exceptions;

use Throwable;
use Illuminate\Http\Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (NotFoundHttpException $e, $request) {
            if (!$request->is('api/*')) {
                return response()->view('page-404')->setStatusCode(Response::HTTP_NOT_FOUND);
            }
        });
    }
}

Test

In your controller simply abort(404) in your controller function it's will redirect to page "page-404"

abort(404);