Social Facebook Login

Reference URL:

Route::get(‘/facebook/login’, function(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
// Send an array of permissions to request
$login_url = $fb->getLoginUrl([’email’]);

// Obviously you’d do this in blade 🙂
echo ‘Login with Facebook‘;

// Endpoint that is redirected to after an authentication attempt
Route::get(‘/facebook/callback’, function(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
// Obtain an access token.
try {
$token = $fb->getAccessTokenFromRedirect();
} catch (Facebook\Exceptions\FacebookSDKException $e) {

// Access token will be null if the user denied the request
// or if someone just hit this URL outside of the OAuth flow.
if (! $token) {
// Get the redirect helper
$helper = $fb->getRedirectLoginHelper();

if (! $helper->getError()) {
abort(403, ‘Unauthorized action.’);

// User denied the request

if (! $token->isLongLived()) {
// OAuth 2.0 client handler
$oauth_client = $fb->getOAuth2Client();

// Extend the access token.
try {
$token = $oauth_client->getLongLivedAccessToken($token);
} catch (Facebook\Exceptions\FacebookSDKException $e) {


// Save for later
Session::put(‘fb_user_access_token’, (string) $token);

// Get basic info on the user from Facebook.
try {
$response = $fb->get(‘/me?fields=id,name,email’);
} catch (Facebook\Exceptions\FacebookSDKException $e) {

// Convert the response to a `Facebook/GraphNodes/GraphUser` collection
$facebook_user = $response->getGraphUser();

// Create the user if it does not exist or update the existing entry.
// This will only work if you’ve added the SyncableGraphNodeTrait to your User model.
$user = App\User::createOrUpdateGraphNode($facebook_user);

// Log the user into Laravel

return redirect(‘/’)->with(‘message’, ‘Successfully logged in with Facebook’);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

Up ↑

%d bloggers like this: