重定向到“找不到页面"页面上的登录页面-Laravel 5.4

问题描述:

我要这样做,以便如果用户未登录并且找不到该页面(不存在的路由),那么该用户将被重定向到登录页面以显示404页面.如果用户已登录,则应显示404页面.我正在使用Laravel 5.4.

I want to make so that if the user is not logged in and the page is not found (unexisting route), the user to be redirected to the login page instead to show the 404 page. If the user is logged in then the 404 page should be displayed. I'm using Laravel 5.4.

您可以在 App \ Exceptions \ Handler @ render 中监听任何异常:

You can listen for any exception in App\Exceptions\Handler@render:

if ($e instanceof NotFoundHttpException) {
    if ( \Auth::guest() ) {
        return redirect()->to('/login');
    }

    return response()->view('errors.404', [], 404);
}

别忘了在文件顶部使用Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException; .

编辑

您必须为所有路由启用会话,以便可以将用户数据保留在未找到的路由上.在您的 app/Http/Kernel.php 中,将以下项目添加到 $ middleware 数组中:

You have to enable the session for all routes so you can have the user data on not found routes. In your app/Http/Kernel.php add the following items to the $middleware array:

protected $middleware = [
    ....

    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];