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

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

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

我在routes.php中添加以下代码:

Route::fallback(function () {
    return redirect('/');
});

这将在发生404错误时重定向至根目录。

4个回答

69

为此,您需要在app/Exceptions/Handler.php文件的render方法中添加几行代码,该方法看起来像这样:

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

2
它可以工作!这是在Laravel 5中处理路由不存在时重定向到主页的正确方法。 - Inspire Shahin
完美的解决方案,谢谢。 - Manjeet Barnala
完美的解决方案! - maruf najm

3

我想提出一个建议,让内容更加清晰。首先,我要感谢被接受的答案给了我启示。但是,在我看来,由于此函数中的每个操作都会返回某些内容,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);
}

1
getStatusCode() :) - senty
@MMMTroy 它不起作用 - undefined

3
您只需按照以下步骤操作:

打开: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);
}

0

从 PHP 8 开始,您可以使用 match 函数:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接