php - 如果 Laravel 的内置身份验证中的身份验证逻辑重定向?

标签 php laravel authentication laravel-5.1

之前有人问过这个问题,我相信我的代码是正确的,但我的行为很奇怪。

根据某些数据库值,我需要在登录后将用户重定向到不同的路由。我认为,为了做到这一点,我只需将我的逻辑放在 app/Http/Middleware/RedirectIfAuthenticated.phphandle 方法中。我的方法目前看起来像这样:

public function handle($request, Closure $next)
{

    if ($this->auth->check()) {
        if($this->auth->user()->sign_up_complete == 1){
            return redirect('/');
        } else {
            if($this->auth->user()->step_one_complete == 0){
                return redirect('/register/step-1');
            } elseif($this->auth->user()->step_two_complete == 0){
                return redirect('/register/step-2');
            } else {
                return redirect('/');
            }
        }
    }

    return $next($request);
}

这不起作用,登录后用户被重定向到 /home。我尝试将 dd($this->auth->user()) 放在 $this->auth->check() 条件中,但它永远不会运行.如果我将它放在该检查之外,那么它会在每个请求上运行。看起来 $this->auth->check() 从未运行过。

我的问题:如果不在这里,这个逻辑应该去哪里?

我也从 AuthController.php Controller 中删除了 protected $redirectTo = '/account';

最佳答案

高级回答:RedirectIfAuthenticated 的目的是防止已经通过身份验证的用户访问登录或注册路由/ View ,因为他们已经登录。

测试:为登录 View 添加书签。然后登录。关闭浏览器或窗口。打开登录书签。您将直接前往用户的家或在 RedirectIfAuthenticated 中指定的地方。

为了 LoginController 的目的,创建一个 redirecTo() 方法,这是 redirectPath() 方法查找的内容,以查看您是否自定义了重定向。

// example
public function redirectTo()
{
    switch (auth()->user()->role) {
        case 'foo':
            return route('foo.home');

        case 'bar':
            return route('bar.home');

        default:
            auth()->logout();
            return route('web.welcome');
    }
}

关于php - 如果 Laravel 的内置身份验证中的身份验证逻辑重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341150/

相关文章:

php - 无法更新 Laravel 模型可见属性

mysql - Laravel 具有整数值的多个连接条件

php - 在 Twig 中设置默认的原始过滤器

PHP 检查特定日期

php - 使用 PHP 和 MySql 匹配两个表中的重复条目

php - [路由 : time. 更新] [URI: time/{time}] 缺少必需的参数

api - Jawbone UP API oAuth 和访问 token

java - Netty 的基本身份 validator

php - Laravel 7.2 中的 RegistersUsers 特性

php - 使用php搜索mysql数据库