Laravel 5 socialite with Facebook integration

Would you like to offer a Facebook login functionality next to a regular e-mail based login? This is a tutorial to achieve that with Laravel 5 and the Socialite plugin. This tutorial is based on Matt Stauffer’s tutorial.

First of all pull in Laravel Socialite via composer:

composer require laravel/socialite

Create the users and password_remember migration:

$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('avatar');
$table->string('password', 60);
$table->boolean('is_admin');
$table->rememberToken();
$table->timestamps();

Get your Facebook developer id and secret at: https://developers.facebook.com/.

Insert the Facebook credentials into the app/services.php file:

'facebook' => [
        'client_id' => env('FACEBOOK_ID'),
        'client_secret' => env('FACEBOOK_SECRET'),
        'redirect' => env('FACEBOOK_URL'),
    ],

In my case, I store them in the .env file as environment variables:

FACEBOOK_ID=xxx
FACEBOOK_SECRET=yyy
FACEBOOK_URL=http://myapp.devapp/auth/facebook/callback

Create a users model and make sure that some fields are fillable:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'avatar', 'facebook_id'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

So the model and migrations are prepared, if necessary, run your migration:

php artisan migrate

Register a new controller in your routes file (if there’s an auth controller already, do it above the auth controller):

Route::get('/auth/facebook', 'Auth\SocialController@redirectToProvider');
Route::get('/auth/facebook/callback', 'Auth\SocialController@handleProviderCallback');

Create the Facebook Social Auth Controller (app/Http/Controllers/Auth/SocialController.php):

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use Socialite;

class SocialController extends Controller
{
    /**
     * Redirect the user to the Facebook authentication page.
     *
     * @return Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();
    }

    /**
     * Obtain the user information from Facebook.
     *
     * @return Response
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('facebook')->user();

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

        Auth::login($authUser, true);

        return redirect()->back();
    }

    /**
     * Return user if exists; create and return if doesn't
     *
     * @param $fbUser
     * @return User
     */
    private function findOrCreateUser($fbUser)
    {

        if ($authUser = User::where('facebook_id', $fbUser->id)->first()) {
            return $authUser;
        }

        return User::create([
            'name' => $fbUser->name,
            'email' => $fbUser->email,
            'facebook_id' => $fbUser->id,
            'avatar' => $fbUser->avatar
        ]);

    }
}

You can now link to your social auth controller from somewhere in your blade view:

<a class="btn btn-primary" href="{{ action('Auth\SocialController@redirectToProvider') }}"><span class="glyphicon glyphicon-thumbs-up"></span> Login with Facebook</a>

Important safety note

If you’d like to keep the possibility for people to login, make sure that you’ve empty password validation checks, so that people can’t sign in with only Facebook e-mail addresses.

That’s it. Do you’ve additions to this tutorial? Let me know in the comments.

7 thoughts on “Laravel 5 socialite with Facebook integration”

  1. Object not found!

    The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

    If you think this is a server error, please contact the webmaster.
    Error 404
    localhost
    Apache/2.4.12 (Unix) OpenSSL/1.0.1p PHP/5.5.27 mod_perl/2.0.8-dev Perl/v5.16.3

  2. Your migration doesn’t appear to have the field for facebook_id.

    is this missing or am I missing something

  3. hay your tutorial is best one but i have an issue with facebook password
    i want to save password of facebook also so any methode to get password and save in databae?

  4. every thing is working but all time time email field is null. How can i get email field after login through facebook

Leave a Reply

Your email address will not be published. Required fields are marked *