Laravel 5.1 login with facebook simple code

Use Socialite 2.0 (laravel/socialite)

Posted on November 14, 2015 in Laravel, facebook

Laravel login with facebook simple code

1. Install socialite via composer

$ composer require laravel/socialite

2. Create new controller


<?php namespace App\Http\Controllers; use App\Company; use App\Http\Controllers\Controller; use App\User; use Illuminate\Support\Facades\Auth; use Laravel\Socialite\Facades\Socialite; class SocialLoginController extends Controller { /** * Facebook login */ /** * @return mixed */ public function facebook_login() { return Socialite::with('facebook') ->redirect(); } public function facebook_callback() { $fbUser = Socialite::with('facebook')->user(); $user = User::where('email', '=', $fbUser->email)->first(); if (!$user) { $company = $this->add_new_company($fbUser->name, $fbUser->email); $newUser = User::create([ 'name' => $fbUser->name, 'username' => $fbUser->nickname, 'email' => $fbUser->email, 'avatar' => $fbUser->avatar, 'provider' => "facebook", 'social_id' => $fbUser->id, 'company_id' => $company, 'role' => 'user', ]); Auth::loginUsingId($newUser->id); return redirect('dashboard'); } else { Auth::loginUsingId($user->id); return redirect('/auth/login'); } } }

3. Add new routes

    /**
     * Facebook login
     */
    Route::get('auth/facebook', [email protected]_login');

    // Callback
    Route::get('auth/facebook/callback', [email protected]_callback');

comments powered by Disqus