Google social login integration using Laravel Socialite

by Vincy. Last modified on November 27th, 2024.

The social login facilitates users by simplifying the login effort with a single click. It cut shot the manual signup and login process saves time. End users prefer this method and hence your signup rate will increase.

Let us see how to integrate the Google social login feature in a Laravel application. A package named Laravel Socialite supports social logins with Google, Facebook, X, LinkedIn, GitHub and Slack via API.

This package connects the social login flow with the Laravel auth instances. All we need to do is to import and call them from the login handlers.

Laravel Social Login Google

Steps setup Google social login in Laravel

I listed all the steps to build a social login even from building a Laravel project. If you are very familiar with Laravel setup and you have Google client keys, just start from point 4.

  1. Set up a new Laravel project.
  2. Install Laravel Socialite package.
  3. Generate Google OAuth client keys.
  4. Configure Google OAuth keys and callback URL to Laravel.
  5. Build social login routes, app model and controller classes.
  6. Add Google social login button to the template.

If you are looking for the code to integrate Google OAuth login using core PHP, get it from the linked tutorial.

1. Set up a new Laravel project

The first step is to create the laravel-social-login project via composer.

composer create-project laravel/laravel laravel-social-login

Create a database db_laravel_social_login and configure credentials in the Laravel app’s .env file.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_laravel_social_login
DB_USERNAME=root
DB_PASSWORD=

Go to the project location via terminal cd laravel-social-login.  Then, do database migration via php artisan migrate command.

2. Install Laravel Socialite package

Install the Laravel Socialite package to the application.

composer require laravel/socialite

I installed Laravel auth to get the authentication views and the required dependancies.

composer require laravel/ui
php artisan ui vue --auth

Run the npm commands to have the libraries for the login UI components.

npm install

Run build if you are using the Vite tool.

npm run build

Or else if you are using Laravel Mix, then run dev.

npm run dev

With the reference of the Laravel Auth:: instances, the login state handling and redirects are happening.

3. Generate Google OAuth client keys

These are the steps to get the Google OAuth keys. You may be familiar with the below steps if you have already worked with Google services.

  • Login to Google cloud console.
  • Create new project or choose existing one.
  • Choose API and Services.
  • Configure the OAuth consent screen.
  • Choose Credentials->CREATE CREDENTIALS->OAuth client ID.
  • Give the following web client details:
    • Application type: Web Application
    • Authorized JavaScript origin: <your domain>
    • Authorized redirect URIs: <Callback URL>
  • Copy the Client ID and the Secret key.

Google Cloud Brand

Create a new Google console project and configure the OAuth consent screen

google login oauth consent screen

Create OAuth credentials

create google oauth client credentials

google client project setting

Copy the client ID and secret key

Google OAuth Client ID Secret

The above steps are required for any application integrating Google cloud services. In this blog also we have seen examples for integrating Google services in a PHP application. I linked 2 of them below.

  1. Sending email with Gmail XOAUTH2
  2. Writing to Google Sheets API.

4. Configure Google OAuth keys and callback URL to Laravel

There are three configuration as listed below.

  1. Google client ID
  2. Google secret key
  3. Callback URL

Create environmental constants for the client id and secret key in the .env

GOOGLE_CLIENT_ID = paste client id here
GOOGLE_CLIENT_SECRET = paste secret key here

Now, it’s ready to configure the social login keys and URLs to the application config file. Open services.php file in the Laravel application root.

the below code shows the method of configuring Google social login constants with the Laravel.

In the same way the Github, Facebook and other social login configurations can be enabled in this file. I will post all the integrations in the upcoming tutorials.

config/services.php

'google' => [
   'client_id' => env('GOOGLE_CLIENT_ID'),
   'client_secret' => env('GOOGLE_CLIENT_SECRET'),
   'redirect' => 'http://127.0.0.1:8000/google/login/callback',
],

5. Build social login routes, app model and controller classes

This section specifies the changes required on the Laravel routes, models and controllers.

Web routes

Add the following two URL rules to the Laravel web routes. One is for redirecting to the Google OAuth endpoint for sending the authorization request. Then, the other is to call back the Laravel application.

routes/web.php

<?php
Route::get('/google/login/redirect', [GoogleOAuthController::class, 'google_login_redirect'])->name('google_login_redirect');
Route::get('/google/login/callback', [GoogleOAuthController::class, 'google_login_callback']);
?>

User model

The user model will contain the fields come up with the default Laravel authentication system.

Add the provider and the provider_id fields to the User model’s fillable array. Open User model and let the $fillable as shown below.

These two columns are to save the social login provider like Google, Facebook and its unique id belongs to the user logged-in.

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    ...
    protected $fillable = [
        'name',
        'email',
        'password',
        'provider',
        'provider_id',
    ];

    ...
}
?>

Create GoogleOAuthController controller

Make the GoogleOAuthController class using php artisan make:controller GoogleOAuthController
The controller has two functions as listed below.

  1. google_login_redirect: It sends the OAuth request to Google.
  2. google_login_callback: It captures API response in a callback.

In the google_login_callback(), it receives the Google user details and saves to the database.

The User::updateOrCreate() function is used to put the user entry with respect to the unique provider_id. This function returns the authenticatable user object. With this object the Auth::login() turns the user logged in.

app/Http/Controllers/GoogleOAuthController.php.php

<?php

namespace App\Http\Controllers;

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

class GoogleOAuthController extends Controller
{
    public function google_login_redirect() {
        return Socialite::driver('google')->redirect();
    }

    public function google_login_callback() {
        $googleUser = Socialite::driver('google')->user();

        $user = User::updateOrCreate([
            'provider_id' => $googleUser->id,
        ], [
            'name' => $googleUser->name,
            'email' => $googleUser->email,
            'provider' => 'google',
            'provider_id' => $googleUser->id
        ]);
     
        Auth::login($user);
     
        return redirect('/home');
    }
}
?>

6. Add Google social login button to the template

By installing Laravel/ui, it brings the auth templates in to the application. The login.blade.php is the view file that contains the default Laravel login form.

Below code give the Google login button with appropriate link to redirect. Copy this code and put it into the login template.

resources/views/login.blade.php

<div class="row mb-0">
    <div class="col-md-8 offset-md-4">
        <a href="{{ route('google_login_redirect') }}">
            <button type="button" class="btn btn-primary px-4 py-2">
                <img src="images/google-logo.png" width="24" class="mx-1" /> Sign in via Google
            </button>
        </a>
    </div>
</div>

Output

By clicking the “Sign in with Google” button, it will ask to “Continue” access profile via web client.
Allow App to Access Profile

After processing social login request, Google redirects to the callback URL. This callback endpoint turns the logged-in state on and redirects to the dashboard.
Laravel Auth Dashboard Template
Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page