onlinecode

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 this post we will give you information about Integrate Facebook Login Authentication and Register Example in Laravel 5.2 from Scratch. Hear we will give you detail about Integrate Facebook Login Authentication and Register Example in Laravel 5.2 from ScratchAnd how to use it also give you demo for it if it is necessary.

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 IlluminateDatabaseSchemaBlueprint;
  2. use IlluminateDatabaseMigrationsMigration;
  3. class CreateUsersTable extends Migration
  4. {
  5. /**
  6. * Run the migrations.
  7. *
  8. * @return void
  9. */
  10. public functionup()
  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 functiondown()
  27. {
  28. Schema::drop('users');
  29. }
  30. }
use IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;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

  1. namespace App;
  2. use IlluminateFoundationAuthUser 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. }
namespace App;use IlluminateFoundationAuthUser 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',    ];}

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'));
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')) ;

Step5: User Controller

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

app/Http/Controllers/UserController.php

  1. namespace AppHttpControllers;
  2. use IlluminateHttpRequest;
  3. use AppHttpControllersController;
  4. use FacebookFacebookSession;
  5. use FacebookFacebookRedirectLoginHelper;
  6. use FacebookFacebookRequest;
  7. use FacebookFacebookAuthorizationException;
  8. use FacebookFacebookRequestException;
  9. use FacebookGraphObject;
  10. use FacebookGraphUser;
  11. use AppUser;
  12. class UserController extends Controller
  13. {
  14. public functionfacebookLogin(Request $request)
  15. {     
  16. FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
  17. $redirect_url=route('user.fblogin');
  18. $helper=newFacebookRedirectLoginHelper($redirect_url);
  19. $fbloginurl=$helper->getLoginUrl(array('scope'=>'public_profile,email'));
  20. $state=md5(rand());
  21. $request->session()->set('g_state',$state);
  22. returnredirect()->to($fbloginurl);
  23. }
  24. public functionfbSignUp(Request $request)
  25. {
  26. FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
  27. $redirect_url=route('user.fblogin');
  28. $helper=newFacebookRedirectLoginHelper(
  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=(newFacebookRequest(
  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. returnredirect()->route('user.list');
  62. }
  63. public functionlistUser(Request $request){
  64. $users= User::orderBy('id','DESC')->paginate(5);
  65. returnview('users.list',compact('users'))->with('i',($request->input('page',1)-1)*5);;
  66. }
  67. }
namespace AppHttpControllers;use IlluminateHttpRequest;use AppHttpControllersController;use FacebookFacebookSession;use FacebookFacebookRedirectLoginHelper;use FacebookFacebookRequest;use FacebookFacebookAuthorizationException;use FacebookFacebookRequestException;use FacebookGraphObject;use FacebookGraphUser;use AppUser;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);;    }}

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. <!DOCTYPEhtml>
  2. <htmllang="en">
  3. <head>
  4. <metacharset="utf-8">
  5. <metahttp-equiv="X-UA-Compatible"content="IE=edge">
  6. <metaname="viewport"content="width=device-width, initial-scale=1">
  7. <title>Integrate Facebook Login and Register Example in Laravel 5.2 from Scratch</title>
  8. <linkhref="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css"rel="stylesheet">
  9. </head>
  10. <body>
  11. <divclass="container">
  12. @yield('content')
  13. </div>
  14. </body>
  15. </html>
<!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 >    @yield('content')</div> </body></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. <divclass="row">
  4. <divclass="col-lg-12 margin-tb">
  5. <divclass="pull-left">
  6. <h2>Logged facebook User List</h2>
  7. </div>
  8. <divclass="pull-right">
  9. <aclass="btn btn-success"href="{{ route('user.facebook.login') }}"> Login with Facebook</a>
  10. </div>
  11. </div>
  12. </div>
  13. <tableclass="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
@extends('layouts.default') @section('content')    <div >        <div >            <div >                <h2>Logged facebook User List</h2>            </div>            <div >                <a  href="{{ route('user.facebook.login') }}"> Login with Facebook</a>            </div>        </div>    </div>    <table >        <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

Show Demo

Label :

PHP

OOP

Object Oriented Programming

Laravel PHP Framework

Facebook API

API

Web Development

Hope this code and post will helped you for implement Integrate Facebook Login Authentication and Register Example in Laravel 5.2 from Scratch. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Exit mobile version