Integrate Facebook Login Authentication and Register Example in Laravel 5.2 from Scratch
In my previous post, you learn how to login and register in Laravel 5.2 using auth scaffold.
Now i will tell you that how you can facebook login in your application using facebook graph api and register user if not exist in your database in Laravel 5.2
Why social logins are integrated in website??It's a right way to get right data and user do not need to remember their username and password for that website, by using facebook api user can easily login and you don't need to verify his email id if user login from social plugings.
Step 1: Install Laravel 5.2If Laravel is not installed in your system then first install with following command and get fresh Laravel project.
composer create-project --prefer-dist laravel/laravel blog
When you go through above command then it create blog directory in your system.
Step 2: Create users table and modelNow you will create a User table in your database, first go through with PHP artisan command to create migration file for user table.
So first run this command :php artisan make:migration create_users_table
After fire this command you will see a migration file in database/migrations. You will simply put following code in your migration file to create user table.
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateUsersTable extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public function up()
- {
- Schema::create('users', function (Blueprint $table) {
- $table->increments('id');
- $table->string('name');
- $table->string('email')->unique();
- $table->string('password');
- $table->rememberToken();
- $table->timestamps();
- });
- }
- /**
- * Reverse the migrations.
- *
- * @return void
- */
- public function down()
- {
- Schema::drop('users');
- }
- }
Save this migration file and run following command.
php artisan migrate
app/User.php
- namespace App;
- use Illuminate\Foundation\Auth\User as Authenticatable;
- class User extends Authenticatable
- {
- /**
- * The attributes that are mass assignable.
- *
- * @var array
- */
- protected $fillable = [
- 'name', 'email', 'password',
- ];
- /**
- * The attributes that should be hidden for arrays.
- *
- * @var array
- */
- protected $hidden = [
- 'password', 'remember_token',
- ];
- }
Put following line in your composer file :
"facebook/php-sdk-v4" : "4.0.*"
Update your composer with following command :
sudo composer updateStep4: Route File
Now add following routes in your routes.php
- Route::get('user/login/callback',array('as'=>'user.fblogin','uses'=>'UserController@fbSignUp')) ;
- Route::get('user/facebook/login',array('as'=>'user.facebook.login','uses'=>'UserController@facebookLogin')) ;
- Route::get('facebook-user',array('as'=>'user.list','uses'=>'UserController@listUser')) ;
Now create User Controller file in following path app/Http/Controllers/
app/Http/Controllers/UserController.php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Http\Controllers\Controller;
- use Facebook\FacebookSession;
- use Facebook\FacebookRedirectLoginHelper;
- use Facebook\FacebookRequest;
- use Facebook\FacebookAuthorizationException;
- use Facebook\FacebookRequestException;
- use Facebook\GraphObject;
- use Facebook\GraphUser;
- use App\User;
- class UserController extends Controller
- {
- public function facebookLogin(Request $request)
- {
- FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
- $redirect_url = route('user.fblogin');
- $helper = new FacebookRedirectLoginHelper($redirect_url);
- $fbloginurl = $helper->getLoginUrl(array('scope' => 'public_profile,email'));
- $state = md5(rand());
- $request->session()->set('g_state', $state);
- return redirect()->to($fbloginurl);
- }
- public function fbSignUp(Request $request)
- {
- FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
- $redirect_url = route('user.fblogin');
- $helper = new FacebookRedirectLoginHelper(
- $redirect_url,
- config('services.facebook.APP_ID'),
- config('services.facebook.APP_SECRET')
- );
- try
- {
- $session = $helper->getSessionFromRedirect();
- } catch (FacebookRequestException $ex)
- {
- return $ex->getMessage();
- } catch (\Exception $ex)
- {
- return $ex->getMessage();
- }
- if (isset($session) && $session){
- try
- {
- $user_profile = (new FacebookRequest(
- $session, 'GET', '/me?fields=id,name,first_name,last_name,email,photos'
- ))->execute()->getGraphObject(GraphUser::className());
- if (User::where('email',$user_profile->getProperty("email"))->first())
- {
- //logged your user via auth login
- }else{
- //register your user with response data
- }
- } catch (FacebookRequestException $e)
- {
- echo "Exception occured, code: " . $e->getCode();
- echo " with message: " . $e->getMessage();
- }
- }
- return redirect()->route('user.list');
- }
- public function listUser(Request $request){
- $users = User::orderBy('id','DESC')->paginate(5);
- return view('users.list',compact('users'))->with('i', ($request->input('page', 1) - 1) * 5);;
- }
- }
Now you will create directory with name 'layouts' in following path resources/views/ and create default.blade.php
within that folder resources/views/layouts/
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Integrate Facebook Login and Register Example in Laravel 5.2 from Scratch</title>
- <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
- </head>
- <body>
- <div class="container">
- @yield('content')
- </div>
- </body>
- </html>
Now create users directory and then create list.blade.php
file in following pathresources/views/users
- @extends('layouts.default')
- @section('content')
- <div class="row">
- <div class="col-lg-12 margin-tb">
- <div class="pull-left">
- <h2>Logged facebook User List</h2>
- </div>
- <div class="pull-right">
- <a class="btn btn-success" href="{{ route('user.facebook.login') }}"> Login with Facebook</a>
- </div>
- </div>
- </div>
- <table class="table table-bordered">
- <tr>
- <th>No</th>
- <th>Name</th>
- <th>Login Time</th>
- </tr>
- @foreach ($users as $user)
- <tr>
- <td>{{ ++$i }}</td>
- <td>{{ $user->name }}</td>
- <td>{{ $user->updated_at->diffForHumans() }}</td>
- </tr>
- @endforeach
- </table>
- {!! $users->render() !!}
- @endsection
To get Facebook APP_ID and Facebook APP_SECRET, Configure your app in facebook first and there you will get Facebook APP_ID and Facebook APP_SECRET that will used for authentication.
Click here to see step-by-step guide to :-Register and Configure an App
Now You can start to authenticate your application with facebook login and sign-up using facebook open graph in Laravel 5.2