Home > other >  How to redirect to 404 use NotFoundHttpException on Handle.php laravel 8
How to redirect to 404 use NotFoundHttpException on Handle.php laravel 8

Time:11-20

i want to redirect all 404 error to home page with handle.php , i use laravel 8 please help me.

    <?php

namespace App\Exceptions;

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

use Throwable;

class Handler extends ExceptionHandler
    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (NotFoundHttpException $e, $request) {
          
        });
    }

CodePudding user response:

You can just return redirect back to the home page :

$this->renderable(function(NotFoundHttpException $ex, $request) {
    return redirect('/');
})

but it will produce a 302 status code instead of 404 but if you want to produce a 404 but still show the homepage.

$this->renderable(function(NotFoundHttpException $ex, $request) {
    return response()->view('homepage', [], 404);
})

Error Handling - Rendering Exceptions

  • Related