laravel-5laravel-routing

Redirect to homepage if route doesnt exist in Laravel 5


/** 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?


Solution

  • 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);
            }
        }