Social Login in Laravel 5.6 using Socialite

1022
social login in laravel kodementor

Social login is becoming essential for any web applications that require registration and login. Social login helps in the faster registration process and valid emails. Today, we are going to integrate laravel/socialite package in our application. Laravel provides built-in authentication. We are going to modify the same according to our need. So, let’s get started.

1Installing Laravel and Setting up

First of all, we will install a fresh laravel 5.6 application. To do this, we will run below command:

composer create-project laravel/laravel laravelsocial

Setup Database

This will create a project with latest version of laravel. Now, lets setup our database. Open your .env file (If you don’t see any, make a duplicate of .env.example file and rename it to .env), and enter your database details. My setup looks like below:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelsocial
DB_USERNAME=root
DB_PASSWORD=secret
 

2Creating default Authentication

Laravel provides default authentication system. It automatically creates routes, controller and views for us. Thus it makes us easy. We will modify this default authentication. To create authentication in our application, run the following command:

php artisan make:auth

3Create migrations and tables

We have our login registration scafilding, now we will create migrations for table. Go to database/migrations directory and open create_users_table and add column to store provider id. Your final migration looks like below:

increments('id');
            $table->string('name');
            $table->string('email')->unique()->nullable();
            $table->string('password')->nullable();
            $table->string('provider_id')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

After your configuration is complete, migrate the migration. Simply run the following command.

php artisan migrate

4Configure User Model

We have successfully migrated our tables but we need to make the column fullable. To do this, simply add the following code in your app/User.php

    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    protected $fillable = [
        'name', 'email', 'password', 'provider_id'
    ];

5Install Socialite package and Configure

Now, we are on our real business. Let’s install socialite package using composer. To do this, run the following command.

composer require laravel/socialite

This will download all the dependencies of this package in your vendor folder. Now, you we need to register service provider for this. Add service provider class in config/app.php file:

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

Similarly, we need to add alias in this file as below:

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

6Register Provider in Application

After successfully installing our package, its time to configure our provider setting in our environment. You can learn how to get provider credentials i.e. client id, client secret and redirect url from this article.

We will use Facebook, Twitter and Google login for this tutorial purpose. Add the following details in your .env file.

TWITTER_CONSUMER_KEY=lOF9jL2jXG7GhYBUWYJAAgY3d5A
TWITTER_CONSUMER_SECRET=9cMrU1PcucSq8NCJHnAOPSNfHxSK5yWGxlNCPEvhIQL9JM1egDm
TWITTER_ACCESS_TOKEN=954024495710285824-l6YG05UX068ssLCmWG8wR4XvaB4I9Kh9
TWITTER_ACCESS_TOKEN_SECRET=SgcnJw5r1D3dFTS8SocVymDlVSzf4sWrZn9rYE7kcbJhpR

FB_CLIENT_ID=1521686922148289
FB_CLIENT_SECRET=ff1318517a9e3131593fh144ac39589c64
FB_REDIRECT='http://laravelsocial.test/auth/login/facebook/callback'

GOOGLE_CLIENT_ID=461911244981-t964qprHb5lshbuv6lqfs1bedtu54kq6bd.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=S7a0UsJlPYZRMCJwNaJDSpidnj
GOOGLE_REDIRECT='http://127.0.0.1/auth/login/google/callback'

Now open app/services.php file and add the following configurations in it.


'twitter' => [
        'client_id'     => env('TWITTER_CLIENT_ID'),
        'client_secret' => env('TWITTER_CLIENT_SECRET'),
        'redirect'      => env('TWITTER_URL'),
],

'facebook' => [
        'client_id'     => env('FB_CLIENT_ID'),
        'client_secret' => env('FB_CLIENT_SECRET'),
        'redirect'      => env('FB_URL'),
],


'google' => [
        'client_id'     => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect'      => env('GOOGLE_REDIRECT'),
],

Note: Above credentials are for demo purpose. You need to get your own credentials

7Configure Route

Now, it’s time to setup our routes. You need two routes, one for redirecting user to the provider and another for receiving callback from provider.

Route::get('auth/login/{social}','Auth\SocialLoginController@redirectToProvider');
Route::get('auth/login/{social}/callback','Auth\SocialLoginController@handleProviderCallback');

8Create Controller and Modify it

You can handle the login with login controller but I prefer that social login is different that normal login. So, I have created a different controller for Social login. Create a controller by running below command.

php artisan make:controller Auth/SocialLoginController

This will create a controller at directory app/Http/Controllers/Auth. Open it and modify. Final controller looks like below:

redirect();
    }

   /**
    * Obtain the user information from Social Logged in.
    * @param $social
    * @return Response
    */
   public function handleProviderCallback($social)
   {
        $user = Socialite::driver($social)->user();

        // $authUser = $this->findOrCreateUser($user, $provider);
        $authUser = User::where('provider_id', $user->id)->first();
        if ($authUser) {
            $loginUser = $authUser;
        } else {
            $loginUser = User::create([
                'name' => $user->name,
                'email' => $user->email,
                'provider_id' => $user->id
            ]);
        }

        Auth::login($loginUser, true);

        return redirect('/');
   }
}

9Create Views

I will use bootstrap to beautify my design. I will first create a default.blade.php as a master template. Master template looks like below:





    
    
    
    
    
    

    
    
    
    




    
    
@yield('content')

Now, we will modify our login blade for social login. So our final page looks like below:

@extends('layouts.app')

@section('content')
{{ __('Login') }}

@csrf
@if ($errors->has('email')) {{ $errors->first('email') }} @endif
@if ($errors->has('password')) {{ $errors->first('password') }} @endif
@endsection

That’s it. You have successfully integrated social login in your application. You can find more about the package in laravel official documentation. https://laravel.com/docs/5.6/socialite

1 COMMENT

  1. Hey webmaster
    When you write some blogs and share with us,that is a hard work for you but share makes you happly right?
    yes I am a blogger too,and I wanna share with you my method to make some extra cash,not too much
    maybe $100 a day,but when you keep up the work,the cash will come in much and more.more info you can checkout my blog.
    http://bit.ly/makemoneymethod2018
    good luck and cheers!

LEAVE A REPLY

Please enter your comment!
Please enter your name here