Integrate Facebook Login Authentication and Register Example in Laravel 5.2 from Scratch

Integrate Facebook Login Authentication and Register Example in Laravel 5.2 from Scratch

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.2

If 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 model

Now 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.


  1. use Illuminate\Database\Schema\Blueprint;
  2. use Illuminate\Database\Migrations\Migration;
  3. class CreateUsersTable extends Migration
  4. {
  5. /**
  6. * Run the migrations.
  7. *
  8. * @return void
  9. */
  10. public function up()
  11. {
  12. Schema::create('users', function (Blueprint $table) {
  13. $table->increments('id');
  14. $table->string('name');
  15. $table->string('email')->unique();
  16. $table->string('password');
  17. $table->rememberToken();
  18. $table->timestamps();
  19. });
  20. }
  21. /**
  22. * Reverse the migrations.
  23. *
  24. * @return void
  25. */
  26. public function down()
  27. {
  28. Schema::drop('users');
  29. }
  30. }

Save this migration file and run following command.

php artisan migrate

app/User.php


  1. namespace App;
  2. use Illuminate\Foundation\Auth\User as Authenticatable;
  3. class User extends Authenticatable
  4. {
  5. /**
  6. * The attributes that are mass assignable.
  7. *
  8. * @var array
  9. */
  10. protected $fillable = [
  11. 'name', 'email', 'password',
  12. ];
  13. /**
  14. * The attributes that should be hidden for arrays.
  15. *
  16. * @var array
  17. */
  18. protected $hidden = [
  19. 'password', 'remember_token',
  20. ];
  21. }
Step3: Update Composer File to add Facebook libraries

Put following line in your composer file :

"facebook/php-sdk-v4" : "4.0.*"

Update your composer with following command :

sudo composer update
Step4: Route File

Now add following routes in your routes.php


  1. Route::get('user/login/callback',array('as'=>'user.fblogin','uses'=>'UserController@fbSignUp')) ;
  2. Route::get('user/facebook/login',array('as'=>'user.facebook.login','uses'=>'UserController@facebookLogin')) ;
  3. Route::get('facebook-user',array('as'=>'user.list','uses'=>'UserController@listUser')) ;
Step5: User Controller

Now create User Controller file in following path app/Http/Controllers/

app/Http/Controllers/UserController.php

  1. namespace App\Http\Controllers;
  2. use Illuminate\Http\Request;
  3. use App\Http\Controllers\Controller;
  4. use Facebook\FacebookSession;
  5. use Facebook\FacebookRedirectLoginHelper;
  6. use Facebook\FacebookRequest;
  7. use Facebook\FacebookAuthorizationException;
  8. use Facebook\FacebookRequestException;
  9. use Facebook\GraphObject;
  10. use Facebook\GraphUser;
  11. use App\User;
  12. class UserController extends Controller
  13. {
  14. public function facebookLogin(Request $request)
  15. {     
  16. FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
  17. $redirect_url = route('user.fblogin');
  18. $helper = new FacebookRedirectLoginHelper($redirect_url);
  19. $fbloginurl = $helper->getLoginUrl(array('scope' => 'public_profile,email'));
  20. $state = md5(rand());
  21. $request->session()->set('g_state', $state);
  22. return redirect()->to($fbloginurl);
  23. }
  24. public function fbSignUp(Request $request)
  25. {
  26. FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
  27. $redirect_url = route('user.fblogin');
  28. $helper = new FacebookRedirectLoginHelper(
  29. $redirect_url,
  30. config('services.facebook.APP_ID'),
  31. config('services.facebook.APP_SECRET')
  32. );
  33. try
  34. {
  35. $session = $helper->getSessionFromRedirect();
  36. } catch (FacebookRequestException $ex)
  37. {
  38. return $ex->getMessage();
  39. } catch (\Exception $ex)
  40. {
  41. return $ex->getMessage();
  42. }
  43. if (isset($session) && $session){
  44. try
  45. {
  46. $user_profile = (new FacebookRequest(
  47. $session, 'GET', '/me?fields=id,name,first_name,last_name,email,photos'
  48. ))->execute()->getGraphObject(GraphUser::className());
  49. if (User::where('email',$user_profile->getProperty("email"))->first())
  50. {
  51. //logged your user via auth login
  52. }else{
  53. //register your user with response data
  54. }
  55. } catch (FacebookRequestException $e)
  56. {
  57. echo "Exception occured, code: " . $e->getCode();
  58. echo " with message: " . $e->getMessage();
  59. }
  60. }
  61. return redirect()->route('user.list');
  62. }
  63. public function listUser(Request $request){
  64. $users = User::orderBy('id','DESC')->paginate(5);
  65. return view('users.list',compact('users'))->with('i', ($request->input('page', 1) - 1) * 5);;
  66. }
  67. }
Step 6: Create Laravel Blade File

Now you will create directory with name 'layouts' in following path resources/views/ and create default.blade.php within that folder resources/views/layouts/

resources/views/layouts/default.blade.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>Integrate Facebook Login and Register Example in Laravel 5.2 from Scratch</title>
  8. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
  9. </head>
  10. <body>
  11. <div class="container">
  12. @yield('content')
  13. </div>
  14. </body>
  15. </html>

Now create users directory and then create list.blade.phpfile in following pathresources/views/users

resources/views/users/list.blade.php
  1. @extends('layouts.default')
  2. @section('content')
  3. <div class="row">
  4. <div class="col-lg-12 margin-tb">
  5. <div class="pull-left">
  6. <h2>Logged facebook User List</h2>
  7. </div>
  8. <div class="pull-right">
  9. <a class="btn btn-success" href="{{ route('user.facebook.login') }}"> Login with Facebook</a>
  10. </div>
  11. </div>
  12. </div>
  13. <table class="table table-bordered">
  14. <tr>
  15. <th>No</th>
  16. <th>Name</th>
  17. <th>Login Time</th>
  18. </tr>
  19. @foreach ($users as $user)
  20. <tr>
  21. <td>{{ ++$i }}</td>
  22. <td>{{ $user->name }}</td>
  23. <td>{{ $user->updated_at->diffForHumans() }}</td>
  24. </tr>
  25. @endforeach
  26. </table>
  27. {!! $users->render() !!}
  28. @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

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort serdivan escort sapanca escort karasu escort hendek escort ankara escort
sakarya escort kızlar sakarya escort kaliteli sakarya escort vip sakarya escort elit sakarya escort bayan sakarya escort adresleri.