Felix
Felix

Reputation: 2661

Laravel Socialite pass and retrieve custom data?

I'm currently adding Socialite to my website to allow users to log in from Facebook.

public function redirectToProviderFacebook() {
    return Socialite::driver('facebook')->redirect();
}

public function handleProviderCallbackFacebook() {
    $userSocial = Socialite::driver('facebook')->user();
    $email = $userSocial->getEmail();

    if (User::where('email', $email)->count() > 0) {
        // log them in
        Auth::login(User::where('email', $email)->first());
        return redirect()->route('home')->with('info', "You are now signed in.");
    } else {
        // register an account and log them in
    }
} 

During normal user registration, I ask for three things: username, email and password. The username and email are things you cannot change on my site, ever, as their usernames are bound to many things.

The problem with logging in with Facebook is that I have to register new users in the callback function. Therefore, I can't ask them for what they want their usernames to be.

Is there a way I could perhaps prompt the user for their preferred username? Then do the redirect like this:

return Socialite::driver('facebook')->with('username', $request->username)->redirect();

Then retrieve that data to use it for auth registration in the callback function?

Upvotes: 3

Views: 4366

Answers (2)

Sr.PEDRO
Sr.PEDRO

Reputation: 2067

For some reason, Optional Parameters didn't work for me, so i ended up by using session to pass variables from redirect method to the callback method. it's not the best way to do it, but it does the trick.

public function redirectToFacebookProvider()
{
    // save anything you will need later, for example an url to come back to
    Session::put('url.intended', URL::previous());

    return Socialite::driver('facebook')->redirect(); 
}

public function handleFacebookProviderCallback()
{
    // handling....

    $url = Session::get('url.intended', url('/'));
    Session::forget('url.intended');

    return redirect($url);
}

Obtained this answer from https://laracasts.com/discuss/channels/laravel/socialite-return-parameters-in-callback?page=0

And from Sending additional parameters to callback uri in socialite package for laravel

Upvotes: 4

Rahul Sharma
Rahul Sharma

Reputation: 622

i am not sure about facebook, but for github its working fine. Try this:

public function socialLogin($loginFrom){
    return Socialite::driver('github') >redirectUrl('http://your-domain.com/callback?data=123')->redirect();
}

on github app you need to put only: http://your-domain.com/callback

Upvotes: 0

Related Questions