Laravel 5.2 How To redirect All 404 Errors to Homepage Laravel 5.2 How To redirect All 404 Errors to Homepage laravel laravel

Laravel 5.2 How To redirect All 404 Errors to Homepage


For that, you need to do add few lines of code to render method in app/Exceptions/Handler.php file.

public function render($request, Exception $e){       if($this->isHttpException($e))    {        switch (intval($e->getStatusCode())) {            // not found            case 404:                return redirect()->route('home');                break;            // internal error            case 500:                return \Response::view('custom.500',array(),500);                break;            default:                return $this->renderHttpException($e);                break;        }    }           return parent::render($request, $e);      }


For me with php 7.2 + Laravel 5.8, it works like a boss.I changed the render method (app/Exceptions/Handler.php).Therefore, we have to check if the exception is an HTTP exception, because we are calling the getStatusCode () method, which is available only in HTTP exceptions.If the status code is 404, we may return a view (for example: errors.404) or redirect to somewhere or route (home).

app/Exceptions/Handler.php

public function render($request, Exception $exception)    {        if($this->isHttpException($exception)) {            switch ($exception->getStatusCode()) {                // not found                case 404:                    return redirect()->route('home');                    break;                // internal error                case 500:                    return \Response::view('errors.500', [], 500);                    break;                default:                    return $this->renderHttpException($exception);                    break;            }        } else {            return parent::render($request, $exception);        }    }

To test: Add abort(500); somewhere in the flow of your controller to view the page/route. I used 500, but you can use one of errors code: Abort(404)...

abort(500);

Optionally, we may provide a response:

abort(500, 'What you want to message');