Laravel 8 Socialite Login With Google Example

Now, let's have an example of laravel 8 login with google. This article will give you a simple example of laravel 8 login with your Gmail account. you will learn laravel 8 jetstream login with google.  In this tutorial, we will see how to create laravel 8 socialite login with google using Laravel socialite package. 

In this tutorial, I would like to share with you laravel 8 login with google. How to login with google in Laravel 8 app?. So from this tutorial, you will learn laravel 8 socialite google login system.

Here I will use the Socialite composer package to sign in with Google. So just follow bellow all step for authentication with your social account in you laravel application.

Socialite from laravel makes it very easy to add multiple providers for authentication, in this post let's build an Auth system on top of Laravel’s default Authentication to support login and register using Google.

So if you want to also create this login with a google Gmail account then I will help you step by step instructions. let's follow the tutorial and implement it.

 

You can visit to know more information about laravel socialite from alravel official website.

 

laravel-socialite-example-from-scratch

Let's start laravel social login example tutorial.

 

Step 1 : Installation 

To get started with Socialite, use Composer to add the package to your project's dependencies:

composer require laravel/socialite

 

Step 2 : Configuration

Now add this into providers and aliases array in config/app.php file. 

config/app.php

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

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

 

Step 3 : Create Migration

Now let’s add some fields in our user’s migration provided by laravel to store avatar and provider info along with access_token. Add this to our default users table.

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

        $table->string('avatar')->nullable();
        $table->string('provider', 20)->nullable();
        $table->string('provider_id')->nullable();
        $table->string('access_token')->nullable();

        $table->rememberToken();
        $table->timestamps();
    });
}

 

After this run following command to complete our migration.

php artisan migrate

 

and open app/User.php model to add these fields in fillable property so we can mass assign them later.

app/User.php

protected $fillable = [
     'name', 'email', 'password',
     'avatar', 'provider_id', 'provider',
     'access_token'
];

//You can also use below statement 

protected $guarded = ['*'];

 

Step 4 : Create Oauth App

Before using Socialite, you will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in config/services.php configuration file.

 

Visit this below url to get your client_id and client_secret.

 

https://console.developers.google.com

 

and add client_id and client_secret in config/services.php file

config/services.php

'google' => [
    'client_id'     => env('GL_ID'),
    'client_secret' => env('GL_SECRET'),
    'redirect'      => env('APP_URL') . '/oauth/google/callback',
],

 

Step 5 : Setup Route

We will need three routes, one for showing the list of buttons for providers, another for Redirect to the provider for authentication and last one to handle the callback from provider once authorized.

routes/web.php

Route::get('auth/social', 'Auth\LoginController@show')->name('social.login');
Route::get('oauth/{driver}', 'Auth\LoginController@redirectToProvider')->name('social.oauth');
Route::get('oauth/{driver}/callback', 'Auth\LoginController@handleProviderCallback')->name('social.callback');

 

Step 6 : Setup Controller

Now visit your app/Http/Controllers/Auth/LoginController and add this following code.

app/Http/Controllers/Auth/LoginController.php

namespace App\Http\Controllers\Auth;

use App\User;
use Exception;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected $providers = [
        'google'
    ];

    public function show()
    {
        return view('auth.login');
    }

    public function redirectToProvider($driver)
    {
        if( ! $this->isProviderAllowed($driver) ) {
            return $this->sendFailedResponse("{$driver} is not currently supported");
        }

        try {
            return Socialite::driver($driver)->redirect();
        } catch (Exception $e) {
            // You should show something simple fail message
            return $this->sendFailedResponse($e->getMessage());
        }
    }

  
    public function handleProviderCallback( $driver )
    {
        try {
            $user = Socialite::driver($driver)->user();
        } catch (Exception $e) {
            return $this->sendFailedResponse($e->getMessage());
        }

        // check for email in returned user
        return empty( $user->email )
            ? $this->sendFailedResponse("No email id returned from {$driver} provider.")
            : $this->loginOrCreateAccount($user, $driver);
    }

    protected function sendSuccessResponse()
    {
        return redirect()->intended('home');
    }

    protected function sendFailedResponse($msg = null)
    {
        return redirect()->route('social.login')
            ->withErrors(['msg' => $msg ?: 'Unable to login, try with another provider to login.']);
    }

    protected function loginOrCreateAccount($providerUser, $driver)
    {
        // check for already has account
        $user = User::where('email', $providerUser->getEmail())->first();

        // if user already found
        if( $user ) {
            // update the avatar and provider that might have changed
            $user->update([
                'avatar' => $providerUser->avatar,
                'provider' => $driver,
                'provider_id' => $providerUser->id,
                'access_token' => $providerUser->token
            ]);
        } else {
            // create a new user
            $user = User::create([
                'name' => $providerUser->getName(),
                'email' => $providerUser->getEmail(),
                'avatar' => $providerUser->getAvatar(),
                'provider' => $driver,
                'provider_id' => $providerUser->getId(),
                'access_token' => $providerUser->token,
                // user can use reset password to create a password
                'password' => ''
            ]);
        }

        // login the user
        Auth::login($user, true);

        return $this->sendSuccessResponse();
    }

    private function isProviderAllowed($driver)
    {
        return in_array($driver, $this->providers) && config()->has("services.{$driver}");
    }
}

 

So we can check a user if their account contains a email or not. So how can we do that, just see below code.

 protected function loginOrCreateAccount($providerUser, $driver) {

    // check for already has account
    $user = User::where('email', $providerUser->getEmail())->first();

// if user already found
        if( $user ) {
            // update the avatar and provider that might have changed
            $user->update([
                'avatar' => $providerUser->avatar,
                'provider' => $driver,
                'provider_id' => $providerUser->id,
                'access_token' => $providerUser->token
            ]);
        } else {
              if($providerUser->getEmail()){ //Check email exists or not. If exists create a new user
               $user = User::create([
                  'name' => $providerUser->getName(),
                  'email' => $providerUser->getEmail(),
                  'avatar' => $providerUser->getAvatar(),
                  'provider' => $driver,
                  'provider_id' => $providerUser->getId(),
                  'access_token' => $providerUser->token,
                  'password' => '' // user can use reset password to create a password
            ]);

             }else{
            
            //Show message here what you want to show
            
           }
      }

      // login the user
        Auth::login($user, true);
        return $this->sendSuccessResponse();
  }

 

Now let's create the view for the login screen.

 

Step 7 : Create Blade File

Create our blade file to show login button. To create login button for corresponding socialite system. Just paste this below code to you resources/views/auth/login.php file.

resources/views/auth/login.php

 

Now visit this below URL 

 

URL
 http://localhost:8000/login

 

Read more : Captcha Code Example using Botdetect Package in Laravel

 

To check whether it works or not. Hope it can help you.

 

#laravel #laravel-8x #login-with-google #laravel-socialite #authentication