Laravel 5 Tutorial : Create Socialite Facebook Login in laravel 5.3

Laravel 5.3 tutorial for beginners : working with Socialite Plugin, how to login/register Using Facebook Authentication For Login in Laravel 5? laravel socialite facebook example

Laravel 5.3 Tutorial for beginners - Working with Laravel Socialite Plugin, how to Using Facebook Authentication For Login or register in Laravel 5.3? Laravel Sociallite Plugin can handle integration with facebook login/register, google plus, twitter, github login, etc.

I assume before doing this lessons, you must learn how to make auth in Laravel 5.3, please read Authentication Login & Registration Form + Bootstrap in laravel 5.3.

Using Facebook Authentication For Login in Laravel 5

First, we will create new Laravel project, read Create project in laravel 5.3
Following this command

cd c:\server\htdocs
....
composer create-project --prefer-dist laravel/laravel sociallogin

Next, add new database, called "social_login"

Next, setup connection to your "social_login" database with configuration your .ENV file,

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=social_login
DB_USERNAME=root
DB_PASSWORD=yourpassword

Next, create Authentication Login & Registration Form that default from laravel 5.3, this tutorial hasbeen posted on this link.
or you can following this command

php artisan make:auth

Installing Socialite

How to install Socialite using composer? just following this command.

composer require laravel/socialite

Than, we nedd to add provider and aliases to the config/app.php file,

'providers' => [
    // Other service providers...
    Laravel\Socialite\SocialiteServiceProvider::class,
],

and add the aliases
Facebook Login in laravel 5.3


'aliases' => [
    // Other service aliases...
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

Setting Facebook Login Apps

To create new facebook apps, goes here https://developers.facebook.com/ and create your app.

 Socialite Facebook Login in laravel 5.3

Socialite Facebook Login in laravel 5.3
On the app dashboard you will see all important data that we need for configuring Laravel Socialite.

Next, In the config/services.php folder add credentials for facebook app :

'facebook' => [
    'client_id' => '765774933545982', // configure with your app id
    'client_secret' => 'c79c7a2d24d3f828e62272cc51acdaaf', // your app secret
    'redirect' => '', // leave blank for now
    ],

Next, create new controller, create new cotroller following this command

php artisan make:controller SocialAuthController

In the SocialAuthController.php, we need two method like redirect() and callback().

<?php
namespace App\HttpControllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\SocialAccountService;
use Socialite; // socialite namespace
class SocialAuthController extends Controller
{
    // redirect function
    public function redirect(){
      return Socialite::driver('facebook')->redirect();
    }
    // callback function
    public function callback(SocialAccountService $service){
      // when facebook call us a with token
    }
}

Next, add new routes,

Route::get('/redirect', 'SocialAuthController@redirect');
Route::get('/callback', 'SocialAuthController@callback');

Now this is a part when we need to go back to the facebook configuration in service.php and update redirect url.

We are going to set this field to full url of the callback route. In our case when we are using PHP development server which is served on http://localhost:8080 by default, our final config/services.php will look like :

'facebook' => [
    'client_id' => '765774933545982', // configure with your app id
    'client_secret' => 'c79c7a2d24d3f828e62272cc51acdaaf', // your app secret
    'redirect' => 'http://localhost:8080/callback', // leave blank for now
    ],

After we have done, we need to create an facebook login link in Login page and that stored on \resources\views\auth\login.blade.php
Just add this code :

<a class="btn btn-link" href="redirect">Facebook Login</a>

Than, lets try your login apps by following this url and Click login using Facebook

http://localhost:8080/login

To get this app work at the first time, you need to confirm that you allow this app to use your data.
Socialite Facebook Login in laravel 5.3
And if you allow this app, you will get nothing dor this step, we must continue to code.

Save All Facebook Data into Databases

First, we need to set the "password" to be "nullable" value in "...._create_users_table.php" migration, that will looking like this :

Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password')->nullable();
$table->rememberToken();
$table->timestamps();

Next, create new migration and new model by following this command :

php artisan make:migration create_social_accounts_table --create="social_accounts"
.........
php artisan make:model SocialAccount

Next, inde create_social_accounts_table migration, add this code

Schema::table('social_accounts', function (Blueprint $table) {
$table->integer('user_id');
$table->string('provider_user_id');
$table->string('provider');
$table->timestamps();
});

and run this command

php artisan migrate:refresh

Next, in our SocialAccount.php Model, add this code

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SocialAccount extends Model
{
  protected $fillable = ['user_id', 'provider_user_id', 'provider'];
  public function user()
  {
    return $this->belongsTo(User::class);
  }
}

Next, to can handling service that will try to register user or log in if account already exists. we need to Create new file like "SocialAccountService.php" and stored into "app" folder, than add this code

<?php
namespace App;
use Laravel\Socialite\Contracts\User as ProviderUser;
class SocialAccountService
{
    public function createOrGetUser(ProviderUser $providerUser)
    {
        $account = SocialAccount::whereProvider('facebook')
            ->whereProviderUserId($providerUser->getId())
            ->first();
        if ($account) {
            return $account->user;
        } else {
            $account = new SocialAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'facebook'
            ]);
            $user = User::whereEmail($providerUser->getEmail())->first();
            if (!$user) {
                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                ]);
            }
            $account->user()->associate($user);
            $account->save();
            return $user;
        }
    }
}

This soure will try to find provider's account in the databases and if it is not present it will create new user. This method will also try to associate social account with the email address in case that user already has an account.

Now everything is ready to handle facebook's callback to our app.

Last step, we just need to open our contoller "SocialAuthController" and with updated callback method it should look like this :

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\SocialAccountService;
use Socialite; // socialite namespace
class SocialAuthController extends Controller
{
    // redirect function
    public function redirect(){
      return Socialite::driver('facebook')->redirect();
    }
    // callback function
    public function callback(SocialAccountService $service){
      // when facebook call us a with token
      $user = $service->createOrGetUser(Socialite::driver('facebook')->user());
      auth()->login($user);
      return redirect()->to('/home');
    }
}

Now you can open your simple facebook login apps and try to login with your facebook.

Video tutorial Socialite Facebook Login in laravel 5.3


Next lessons, we will create login using google plus, twitter, github in laravel project.
See you next lessons...

COMMENTS

Next Recomended


Feel free to code it up and send us a pull request.

Hi everyone, let's me know how much this lesson can help your work. Please Subscribe and Follow Our Social Media 'kodeajaib[dot]com' to get Latest tutorials and will be send to your email everyday for free!, Just hit a comment if you have confused. Nice to meet you and Happy coding :) all ^^



Follow by E-Mail


Name

ADO.NET,3,Ajax,6,Android,9,AngularJS,4,ASP.NET,4,Blogger Tutorials,7,Bootstrap,7,C++,1,Codeigniter,2,Cplusplus,6,Crystal Report,6,CSharp,25,Ebook Java,2,FlyExam,1,FSharp,3,Game Development,2,Java,35,JDBC,2,Laravel,84,Lumen,2,MariaDB,2,Ms Access,3,MySQL,31,ODBC,6,OleDB,1,PHP,14,PHP Framework,5,PHP MYSQLI,9,PHP OOP,5,Python,8,Python 3,4,SQL Server,4,SQLite,4,Uncategorized,5,Vb 6,2,Vb.Net,89,Video,48,Vue Js,4,WPF,2,Yii,3,
ltr
item
KODE AJAIB: Laravel 5 Tutorial : Create Socialite Facebook Login in laravel 5.3
Laravel 5 Tutorial : Create Socialite Facebook Login in laravel 5.3
Laravel 5.3 tutorial for beginners : working with Socialite Plugin, how to login/register Using Facebook Authentication For Login in Laravel 5? laravel socialite facebook example
https://1.bp.blogspot.com/-qnl8-eGn-ZE/V_A_wOb6-yI/AAAAAAAACn4/IjRFwpXxkM4hKcaE87aJgiyA3VyFMC6vQCLcB/s320/facebook-login-laravel-tutorial-for-beginner.png
https://1.bp.blogspot.com/-qnl8-eGn-ZE/V_A_wOb6-yI/AAAAAAAACn4/IjRFwpXxkM4hKcaE87aJgiyA3VyFMC6vQCLcB/s72-c/facebook-login-laravel-tutorial-for-beginner.png
KODE AJAIB
https://www.kodeajaib.com/2016/10/laravel-5-create-socialite-facebook-login-laravel.html
https://www.kodeajaib.com/
https://www.kodeajaib.com/
https://www.kodeajaib.com/2016/10/laravel-5-create-socialite-facebook-login-laravel.html
true
3214704946184383982
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy