AmanVaidya
1 year ago

How to pass logged in user data to view from LoginController

Posted 1 year ago by AmanVaidya

I am using socialite to login users from facebook, but how to pass logged in user data from view Here are my file contents

web.php
Route::get('/', function () {
    return view('welcome');
})->name('mainpage');


....
some more routes
....


Route::get('login/facebook', 'Auth\[email protected]');
Route::get('login/facebook/callback', 'Auth\[email protected]');
LoginController.php
public function redirectToProvider()
{
    return Socialite::driver('facebook')->redirect();
}

public function handleProviderCallback()
{
    $facebook = Socialite::driver('facebook')->user();

    $user = $this->findOrCreateUser($facebook);

    //login the user
    Auth::login($user, true);

    //redirect to homepage
    return redirect()->route('mainpage', compact('user'));
}

public function findOrCreateUser($facebook)
{
    $user = User::where('facebook_id', $facebook->id)->first();

    if(!$user) {
        $user = new User;
        $user->name = $facebook->getName();
        $user->facebook_id = $facebook->getId();
        $user->email = $facebook->getEmail();
        $user->gender = $facebook->user['gender'];
        $user->avatar = $facebook->avatar;
        $user->facebook_url = $facebook->profileUrl;
        $user->save();
    } else {
        $user->name = $facebook->getName();
        $user->save();
    }

    return $user;
}
welcome.blade.php
@guest
    You are not logged in!
@endguest

@auth
    Hi {{ $user->name }}
@endauth

I am getting error

Undefined variable: user (View: /path/to/view/welcome.blade.php)

Please sign in or create an account to participate in this conversation.