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

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('/');
}); 

我的 routes.php 文件中有此代码。我想知道如果出现 404 错误如何重定向回主页。这可能吗?

为此,您需要在 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);
        }
    }

我只是想添加一个建议来进一步清理它。我想将接受的答案归功于让我开始。然而,在我看来,由于此函数中的每个操作都会 return 某些内容,因此 switch 和 else 语句会造成一些膨胀。因此,为了稍微清理一下,我会执行以下操作。

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

你可以这样做:

打开:app\Exceptions\Handler.php

在 handler.php 中,您可以替换此代码:

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

通过这个:return redirect('/');

效果不错 ,例如:

public function render($request, Exception $exception)
{
     return redirect('/');
    //return parent::render($request, $exception);
}