如果Laravel 5中不存在路由,则重定向到主页

jes*_*s88 16 laravel-routing laravel-5

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

我在routes.php文件中有这个代码.我想知道如果有404错误,如何重定向回主页.这可能吗?

小智 59

为此,您需要在app/Exceptions/Handler.php文件中添加几行代码来渲染方法,如下所示:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 有用!如果Laravel 5中不存在路由,这是处理重定向到主页的正确方法. (2认同)