20
/** Redirect 404's to home
*****************************************/
App::missing(function($exception)
{
    // return Response::view('errors.missing', array(), 404);
    return Redirect::to('/');
}); 

I have this code in my routes.php file. I am wondering how to redirect back to the home page if there is a 404 error. Is this possible?

justin.esders
  • 1,316
  • 4
  • 12
  • 28

4 Answers4

68

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

public function render($request, Exception $e)
    {
        if($this->isHttpException($e))
        {
            switch ($e->getStatusCode()) 
                {
                // not found
                case 404:
                return redirect()->guest('home');
                break;

                // internal error
                case '500':
                return redirect()->guest('home');
                break;

                default:
                    return $this->renderHttpException($e);
                break;
            }
        }
        else
        {
                return parent::render($request, $e);
        }
    }
ΩlostA
  • 2,501
  • 5
  • 27
  • 63
William Langlois
  • 825
  • 7
  • 10
3

I just want to add a suggestion for cleaning it up a bit more. I'd like to credit the accepted answer for getting me started. In my opinion however since every action in this function will return something, the switch and else statement create a bit of bloat. So to clean it up just a tad, I'd do the following.

public function render($request, Exception $e)
{
    if ($this->isHttpException($e))
    {
        if ($e->getStatusCode() == 404)
           return redirect()->guest('home');

        if ($e->getStatusCode() == 500)
           return redirect()->guest('home');
    }

    return parent::render($request, $e);
}
3dgoo
  • 15,716
  • 6
  • 46
  • 58
MMMTroy
  • 1,256
  • 1
  • 11
  • 20
3

you may Just do this :

open : app\Exceptions\Handler.php

in handler.php you can replace this code :

return parent::render($request, $exception);

by this : return redirect('/');

it works good ,example :

public function render($request, Exception $exception)
{
     return redirect('/');
    //return parent::render($request, $exception);
}
Rachid Loukili
  • 623
  • 6
  • 15
0

From PHP 8 you can use the match func:

if ($this->isHttpException($e)) {
    return match ($e->getStatusCode()) {
        500, 404 => redirect()->guest('/'),
        default => $this->renderHttpException($e),
    };
} else {
    return parent::render($request, $e);
}