【问题标题】:Laravel 5 Redirect from a sub-methodLaravel 5 从子方法重定向
【发布时间】:2015-07-09 13:38:39
【问题描述】:

我正在使用 Socialite 从 facebook 获取用户信息。一切顺利,但我的重定向不起作用

子路线

我了解到无法从子方法进行重定向,或者 任何不在您的路线中的方法。

但是在我登录后我还能如何重定向用户呢?

Facebook 握手成功后我的网址如下所示

http://tmdb.app/auth/login/facebook?code=AQBTKNZIxbfdBruAJBqZ8xx9Qnz...

代码

class SocialController extends Controller {

    public function login(Authenticate $authenticate, Request $request)
    {
        return $authenticate->execute($request->has('code'), $this);
    }

    public function userHasLoggedIn($data)
    {
        $user = User::where('provider_id', $data->id)->first();

        if( !$user )
        {
            $user = User::create([
                'name' => $data->name,
                'email' => $data->email,
                'provider' => 'facebook',
                'provider_id' => $data->id
            ]);
        }

        // NOT WORKING!
        return redirect('test');

    }
}

【问题讨论】:

标签: php laravel redirect


【解决方案1】:

您的登录函数应该处理重定向。

我猜如果用户成功登录,execute 返回 $data,否则返回 false。

class SocialController extends Controller {

    public function login(Authenticate $authenticate, Request $request)
    {
        if($data = $authenticate->execute($request->has('code'), $this))
        {
            $user = User::where('provider_id', $data->id)->first();

            // maybe delegate the user creation to another class/service?
            if( !$user )
            {
                $user = User::create([
                    'name' => $data->name,
                    'email' => $data->email,
                    'provider' => 'facebook',
                    'provider_id' => $data->id
                ]);
            }

        return redirect('test');

        }

    return redirect('fail_view');

    }

}

【讨论】:

  • 拆分用户创建的好主意,UserRepository 对这个有好处吗?
  • 是的,这肯定是一个有趣的改进。如果您要构建复杂的东西,将其作为实现传递给接口将是最佳选择。
  • 我不明白为什么它在这个 laracast 中为 Jeffrey 工作:(截图)prntscr.com/7qp5mu
  • 你有他的routes.php文件截图吗?
  • 当然! (截图)prntscr.com/7qp6t7,谢谢!,他只接触了@login 路线
【解决方案2】:

您可以使用 Laravel 子方法中的 PHP 标头函数来完成。我尝试了它并正常工作。希望对你有帮助。

// You can using the following code $url= url("about-laravel"); header("Location:" . $url); exit; // Or using the following code to redirect and keep set flash message $result= $this->yourMethod(); // return redirect($this->route)->with('flash_message', 'I\'m Flash Message'); for TRUE or NULL for false if( $result ){ return $result; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2015-08-04
    • 2016-04-06
    • 2015-04-08
    • 2015-08-10
    相关资源
    最近更新 更多