Google Login in laravel using Socialite

Nowadays, it's common to provide login functionality using social media platforms like Google, Facebook, Twitter, or developer platforms like GitHub. Normally all users are using Facebook, Gmail etc. So if we provide way for login to our system so they don't have to fill sign up forms or they don't need to remember password for your website and they can easily login using platforms. It will be easier to access your service with social media login and will provide better user experience.

In this tutorial, we will guide you to integrate google login to your application step by step.

For Google login integration in Laravel, you need to go to Google Developer Console and setup google app. it will give you client id and secret and also need to setup entry point and redirect for our application.

Setting up Google Account/App For Login with Google

Perform below steps to create google app and get credentials.

Step 1: Open Google Developer Console and login to your google account.

Step 2: In home page, click on Create project to create new google app or project.

Create new project in google console

Step 3: It will show view like below image. Fill all details and click on create button and it will create new project.

Create new project screen in google console

Step 4: After that, you need to click on left side menu credentials and appear below screen. In this screen, you need to select OAuth client ID:

Create new Oauth client ID google console

Step 5: After that, the below form will be appear. Here From different Application type options select Web application. Once you have select Web application option, then one form will appear on web page. It will ask you some details like name, authorized URLS and Redirect URL set appropriate values and click on save button

Create new Oauth into google console

Step 6: The next screen will be listing screen. OAuth2 Client ID table will display newly created Oauth Client ID. Now click on download button and it will download data into json file.

Downloading google credentials

That json file contains necessary values for setting Laravel login with google or Gmail. We will use that into further code.

For this example, we will use Laravel Socialite as support library.

  • Step 1: Install Laravel Application
  • Step 2: Install Jetstream
  • Step 3: Database Configuration
  • Step 4: Setting Up Google Account in Our Application
  • Step 5: Install Socialite
  • Step 6: User Model Changes
  • Step 7: Create Necessary Routes
  • Step 8: Authentication Functionality
  • Step 9: Create Views
  • Step 10: Running Application

Create New Laravel Application

Let's start with creating fresh Laravel application for this example. If you already have existing application then you can skip this step. As you know you can create new Laravel application with composer using one of the below commands. So open your terminal and enter below command :

    
        laravel new GoogleLogin
        //Or
        composer create-project --prefer-dist laravel/laravel GoogleLogin
    

Here we are using "GoogleLogin" as project name but you can rename it.

Install Jetstream

Laravel Jetstream provides the application's login, registration, email verification, two-factor authentication, session management, API via Laravel Sanctum , and optional team management features in short all authentication and authorization features are provided with Jetstream. However you can customized those components as per your requirements.

Please check Create Laravel Application with Jetstream Authentication for complete step by step installation.

Let's install Jetstream using composer. Enter below command to terminal or command prompt to install Jetstream :

    
composer require laravel/jetstream
    

It will download Laravel Jetstream to our newly created application.

Jetstream provide two frontend stacks. Which are Livewire and Inertia. In this example we will use livewire as frontend. Below command will install Jetstream with Livewire.

    
php artisan jetstream:install livewire
    

After installation we need to install node packages for liveware. Enter below commands to install & compile npm packages :

    
npm install
npm run dev
    

It will take some time to download and install node modules. After that it will show Laravel mix build successfully.

Database Configuration

Now it's time to configure database for our application. If you don't have any database then create new one. After that open your project into text editor and open .env file from root directory. If .env file is missing then copy .env.example and rename it.

    
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=**********
DB_USERNAME=*********
DB_PASSWORD=*********
    

After database configuration, migrate database using below command :

    
php artisan migrate
    

It will create database tables from migration files.

Setting Up Google Account in Our Application

Now our initial application setup is completed. We need to setup Google's secret, client ID and redirect URL to our application. So once again open .env file and add below code at last.

    
GOOGLE_CLIENT_ID = "Your Client ID" 
GOOGLE_CLIENT_SECRET = "Your client secret"
GOOGLE_REDIRECT = "http://127.0.0.1:8000/auth/google/callback" //redirect
    

Install Socialite

As we know we will use Laravel Socialite package to perform google authentication. Open your terminal and enter below command to download and install Socialite package :

    
composer require laravel/socialite
    

After that, configure this package in app.php file, so go to config directory and open app.php file. we need to add Socialite as provider and alias :

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

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

Socialite package works as service in our application so we need to configure it into our configuration file for services. For that, open App\Config\services.php file and make below changes

    
<?php

return [

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    ],

    'postmark' => [
        'token' => env('POSTMARK_TOKEN'),
    ],

    'ses' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ],

    //Add this code
    'google' => [
        'client_id'     => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect'      => env('GOOGLE_REDIRECT')
    ],
];
    

User Model & Migration Changes

Now, We will modify user database table for storing google_id. For that we need to change into user migration and model. Let's create migration using below command :

    
php artisan make:migration add_google_id_column_to_user
    

It will create databas/migrations/********_add_google_id_column_to_user.php file. Let's modify it as per our requirements.

    
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddGoogleIdColumnToUser extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('google_id')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('google_id');
        });
    }
}
    

Open App\Models\User.php and add google_id column to fillable array for mass assignment.

    
protected $fillable = [
    'name',
    'email',
    'password',
    'google_id',//Add this line
];
    

Let's add google column into users table by migrating database. Open terminal and enter below command :

    
php artisan migrate
    

Create Necessary Routes

Let's add route for google login and redirect into our application. Open routes\web.php file and make below changes.

    
<?php

use App\Http\Controllers\GoogleController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified'
])->group(function () {
    Route::get('/dashboard', function () {
        return view('dashboard');
    })->name('dashboard');
});

Route::get('auth/google', [GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
    

Here we added 2 routes in our application. First one will redirect to google login page and second one will handle google login response. Please create those route as per google account like if you changed URL path into your Google console id then it can show 404 Error. So please compare it with Google's Authorized JavaScript Origins and Authorized redirect URLs in google console.

Authentication Functionality

Let's create functionality which will handle operations as per our routing. It's a best practice to create controllers functionality wise separately. In this application we will create new controller called Google Controller to handle all google authentication operations.

Switch back to terminal and enter below command to create Google Controller :

    
php artisan make:controller GoogleController
    

It will create GoogleController.php. Let's modify it as per our requirements.

    
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Exception;
use Auth;

class GoogleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */

    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->user();
            $user = User::where('google_id', $googleUser->id)->first();
            if(!$user){
                $user = User::create([
                    'name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'google_id'=> $googleUser->id,
                    'password' => encrypt('12345678')
                ]);
            }
            Auth::login($user);
            return redirect()->intended('dashboard');
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }   
}
    

Here we have created 2 methods which will handle operations as per routes. First method will redirect Google login page and in second method we will check login status. If user logged in then we will check user into our database and add if not user not found.

Create Views

We have used Jetstream authentication so auth views are already created. So we don't have to create new views. we can easily modify it as per our requirements. Open resources\views\auth\login.blade.php file and modify it :

    
<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label for="email" value="{{ __('Email') }}" />
                <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label for="password" value="{{ __('Password') }}" />
                <x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label for="remember_me" class="flex items-center">
                    <x-jet-checkbox id="remember_me" name="remember" />
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Log in') }}
                </x-jet-button>
            </div>
            <div class="flex items-center justify-end mt-4">
                <a href="{{ url('auth/google') }}">
                    <img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png" style="margin-left: 3em;">
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>
    

Running Application

Now our application is compatible with Google login. For running application run local server using artisan. Open terminal and enter below command to run Laravel application :

    
php artisan serve
    

Open below URL into browser to see output:

    
http://127.0.0.1:8000
    

Share your thoughts

Ask anything about this examples