如何将用户重定向到相应的提供商,例如facebook,twitter in laravel 5.4

时间:2017-06-09 07:35:13

标签: php database laravel-5 laravel-5.4

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Socialite;
use App\User;
use Auth;

class SocialLoginController extends Controller
{

    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }
    public function handleProviderCallback($provider)
    {
        try{
            $user = Socialite::driver($provider)->user();

        }catch(Exception $e){
            return redirect('auth/{$provider}');
        }
        // dd($user);
        $authUser = $this->findOrCreateUser($user);

        Auth::login($authUser, true);

        if($authUser->$provider === 'twitter') {
            return redirect()->intended('https://twitter.com/');
        }

        return redirect()->intended('https://www.facebook.com/');
    }

    Private function findOrCreateUser($providerUser)
    {
        $authUser = User::where('provider_id', $providerUser->id)->first();

        if ($authUser){
            return $authUser;
        }

        return User::create([
            'name' => $providerUser->name,
            'email' => $providerUser->email,
            'provider_id' => $providerUser->id,
            'avatar' => $providerUser->avatar,
            'avatar_original' => $providerUser->avatar_original,
            // 'profileUrl' => $twitterUser->profileUrl
            ]);
    }
}

如何将用户返回给相应的提供商?

这是我的路线

Route::get('auth/{provider}', ['as' => 'auth/{provider}', 'uses' => 'SocialLoginController@redirectToProvider']);
Route::get('auth/{provider}/callback',['as' => 'auth/{provider}/callback', 'uses' => 'SocialLoginController@handleProviderCallback']);

1 个答案:

答案 0 :(得分:0)

$authUser->$provider === 'twitter'更改为您实际需要的正确测试,我想它应该是$provider === 'twitter'