Implementing social logins using socialite in Laravel

Laravel introduced their socialite package for making the implementation of social logins in your application hassle free. In daytoday life we see a lot of websites that allow users to login using their social networking accounts like Facebook, Twitter, Google + etc. Laravel’s socialite package helps us to easily implement this accessibility feature in our websites. Let’s see how.

Steps to create any social networking account login using socialite is as follows:

  • Install Laravel

  • Set the database configuration

  • Install socialite package

  • Add providers and aliases

  • Create the application(Facebook, Twitter etc)

  • Create table using migration

  • Configuration of API key.

The first and second steps are the Laravel basics that you already know, so let’s jump to installing the socialite package and the migration. Download the socialite package using composer.

composer require laravel/socialite

Now you have to add the providers and alises. Go to the app.php file in your configuration directory. Add the following lines of code in that file.


'providers' => [

     // Other service providers…

 Laravel\Socialite\SocialiteServiceProvider::class,

],


'aliases' => [

// Other aliases…

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

],


For the sake of keeping this blog as short we will see how to implement twitter login only using socialite. Now we will go to https://apps.twitter.com/ and create a new twitter app. You will see a page where you could enter your organization url, terms of service url, application name etc.

After filling out all of the information needed you will get redirected to a dashboard. There you will get your client id and secret. Set these credentials in the config/service.php file.


'twitter' => [

     'client_id' => 'your client id',

     'client_secret' => 'your client secret',

     'redirect' => 'http://localhost:8000/callback/twitter',

 ],


Now set fillable property in your app/User.php.


protected $fillable = [

         'name', 'email', 'password', 'provider', 'provider_id'

     ];


Now go to create_user_table.php in app/database add these lines of code:


<?php

 

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

 

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()->nullable();

            $table->string('provider');

            $table->string('provider_id');

            $table->timestamp('email_verified_at')->nullable();

            $table->string('password')->nullable();

            $table->rememberToken()->nullable();

            $table->timestamps();

        });

    }

 

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('users');

    }

}


Now run the migration after entering the code below in app/providers/AppServiceProvider.php.


...

use Illuminate\Support\Facades\Schema;

 

....

function boot()

{

    Schema::defaultStringLength(191);

}


Go ahead and run the migrate command.


php artisan migrate


Add routes for the App in the web.php file.


Route::get('/auth/redirect/{provider}', 'TwitterSocialController@redirect');

 Route::get('/callback/{provider}', 'TwitterSocialController@callback');


Create a controller using artisan command.


php artisan make:controllerTwitterSocialController


Open TwitterSocialController.php file in app/http/controller directory and add the lines of code.


<?php

namespace App\Http\Controllers;

 

use Illuminate\Http\Request;

use Validator,Redirect,Response,File;

use Socialite;

use App\User;

class TwitterSocialController extends Controller

{

    public function redirect($provider)

    {

        return Socialite::driver($provider)->redirect();

    }

 

    public function callback($provider)

    {

               

        $getInfo = Socialite::driver($provider)->user();

         

        $user = $this->createUser($getInfo,$provider);

 

        auth()->login($user);

 

        return redirect()->to('/home');

 

    }

   function createUser($getInfo,$provider){

 

     $user = User::where('provider_id', $getInfo->id)->first();

 

     if (!$user) {

         $user = User::create([

            'name'     => $getInfo->name,

            'email'    => $getInfo->email,

            'provider' => $provider,

            'provider_id' => $getInfo->id

        ]);

      }

      return $user;

   }

}


Run the composer command to generate auth scaffolding files.


composer require laravel/ui

php artisan ui bootstrap --auth


Install npm and open register.blade.php file update the code below.


<hr>

<div class="form-group row mb-0">

     <div class="col-md-8 offset-md-4">

        <a href="{{ url('/auth/redirect/twitter') }}" class="btn btn-primary"><i class="fa fa-twitter"></i> Twitter</a>

    </div>

</div>


In your login.blade.php file in resources/views/auth folder add the lines of code given below.


<hr>

<div class="form-group row mb-0">

     <div class="col-md-8 offset-md-4">

        <a href="{{ url('/auth/redirect/twitter') }}" class="btn btn-primary"><i class="fa fa-twitter"></i> Twitter</a>

    </div>

</div>


Run the php artisan serve command and run twitter login in Laravel.