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.
- use IlluminateDatabaseSchemaBlueprint;
- use IlluminateDatabaseMigrationsMigration;
- class CreateUsersTable extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public functionup()
- {
- 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 functiondown()
- {
- Schema::drop('users');
- }
- }
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
- 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',
- ];
- }
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
- 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'));
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
- 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 functionfacebookLogin(Request $request)
- {
- FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
- $redirect_url=route('user.fblogin');
- $helper=newFacebookRedirectLoginHelper($redirect_url);
- $fbloginurl=$helper->getLoginUrl(array('scope'=>'public_profile,email'));
- $state=md5(rand());
- $request->session()->set('g_state',$state);
- returnredirect()->to($fbloginurl);
- }
- public functionfbSignUp(Request $request)
- {
- FacebookSession::setDefaultApplication(config('services.facebook.APP_ID'),config('services.facebook.APP_SECRET'));
- $redirect_url=route('user.fblogin');
- $helper=newFacebookRedirectLoginHelper(
- $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=(newFacebookRequest(
- $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();
- }
- }
- returnredirect()->route('user.list');
- }
- public functionlistUser(Request $request){
- $users= User::orderBy('id','DESC')->paginate(5);
- returnview('users.list',compact('users'))->with('i',($request->input('page',1)-1)*5);;
- }
- }
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
- <!DOCTYPEhtml>
- <htmllang="en">
- <head>
- <metacharset="utf-8">
- <metahttp-equiv="X-UA-Compatible"content="IE=edge">
- <metaname="viewport"content="width=device-width, initial-scale=1">
- <title>Integrate Facebook Login and Register Example in Laravel 5.2 from Scratch</title>
- <linkhref="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css"rel="stylesheet">
- </head>
- <body>
- <divclass="container">
- @yield('content')
- </div>
- </body>
- </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.php
file in following pathresources/views/users
resources/views/users/list.blade.php
- @extends('layouts.default')
- @section('content')
- <divclass="row">
- <divclass="col-lg-12 margin-tb">
- <divclass="pull-left">
- <h2>Logged facebook User List</h2>
- </div>
- <divclass="pull-right">
- <aclass="btn btn-success"href="{{ route('user.facebook.login') }}"> Login with Facebook</a>
- </div>
- </div>
- </div>
- <tableclass="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
@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
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