如果尝试转到登录屏幕,Laravel 5 将重定向到主页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32424689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:18:41  来源:igfitidea点击:

Laravel 5 redirect to home page if attempting to go to login screen

phplaravelroutinglaravel-5

提问by imperium2335

I have a login screen which is the base url (www.mysite.com/).

我有一个登录屏幕,它是基本 url (www.mysite.com/)。

When a user logs in they are redirected to their home page (/home).

当用户登录时,他们被重定向到他们的主页 (/home)。

But the can still get back to the login page if they go to the root.

但是如果他们转到根目录,仍然可以返回登录页面。

How do I make it so logged in users are sent back to their home page if they are logged in (if they are not, of course they see the login page)?

如果登录的用户已登录(如果没有登录,当然他们会看到登录页面),我该如何做到这一点?

回答by imperium2335

I did this in my router, although I'm not sure if it's the best solution:

我在我的路由器上做了这个,虽然我不确定这是否是最好的解决方案:

Route::get('/', function () {
    if(Auth::check()) {
        return redirect('/dashboard');
    } else {
        return view('auth.login');
    }
});

回答by lordthorzonus

You should use middleware for this.

您应该为此使用中间件。

Laravel 5 has already a 'guest' middleware out of the box you can use, so just doing the following should be enough:

Laravel 5 已经有一个开箱即用的“访客”中间件,您可以使用,因此只需执行以下操作就足够了:

Route::get('/', ['middleware' =>'guest', function(){
  return view('auth.login');
}]);

Then in the middleware file App\Http\Middleware\RedirectIfAuthenticatedyou can specify where the user is redirected to.

然后在中间件文件中,App\Http\Middleware\RedirectIfAuthenticated您可以指定用户重定向到的位置。

The default is /home.

默认为/home

回答by R0bertinski

In my case I had to delete the cookies in my browser in order to fix the /login redirect.

就我而言,我不得不删除浏览器中的 cookie 以修复 /login 重定向。

回答by Amir Bar

When a user is successfully authenticated, they will be redirected to the /home URI, which you will need to register a route to handle. You can customize the post-authentication redirect location by defining a redirectPath property on the AuthController:

当用户成功通过身份验证时,他们将被重定向到 /home URI,您需要注册一个路由来处理。您可以通过在 AuthController 上定义 redirectPath 属性来自定义身份验证后重定向位置:

in your AuthController change the redirectPath property

在您的 AuthController 中更改 redirectPath 属性

protected $redirectPath = '/dashboard';

http://laravel.com/docs/5.1/authentication#Authenticating

http://laravel.com/docs/5.1/authentication#Authenticating

回答by Sara Vaseei

In my case I edited HomeController's construct as given below and worked:

在我的情况下,我编辑了 HomeController 的构造,如下所示并工作:

  public function __construct()
  {
    $this->middleware('auth')->except('index');
  }