Implementing social account authentication is very popular these days. ⁤⁤It is easy and powerful method for user authentication, social account authentication takes less effort from user for registration or login on your system. ⁤⁤there is no need for the user to remember the username and password.

Laravel 11 Socialite -  Implementing Google Sign-In in Your Laravel Application

Table Of Content

1 Prerequisites

1.) PHP version of 8.2
2.) MySql
3.) Google Account

2 Introduction

In this article, I am going to show you how to implementation social account authentication to your Laravel application. We’ll be using Laravel external libraries such as Socialite and Breeze Package. Laravel provides a package to authenticate with OAuth providers using Laravel Socialite. Although, this package is not pre-installed in laravel.

Laravel Socialite supports authentication only for the following social account providers:
  • Facebook
  • Twitter
  • LinkedIn
  • Google
  • GitHub
  • GitLab
  • Bitbucket
  • Slack.

3 Create / Install a Laravel Project

3.1 Install Laravel Project

First, make sure your computer has a composer.
Use the following command to install new Laravel Project.

composer create-project laravel/laravel google-auth-app

Then, navigate to your project directory:

cd google-auth-app

3.2 Configure MySql Database

Upon logging in, the user's record will be stored in the database. This process involves accessing the .env file to input and define the database credentials.

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

4 Install Laravel Packages

We will use Laravel Breeze as an example of our existing authentication implementation.

4.1 Install Breeze Package

Use the following command to Install Laravel Breeze Package

composer require laravel/breeze --dev
After Composer has installed the Laravel Breeze package, you should run the breeze:install Artisan command. This command publishes the authentication views, routes, controllers, and other resources to your application.

php artisan breeze:install
 
php artisan migrate
npm install
npm run dev

4.2 Install Socialite Package

Use the following command to Install Laravel Socialite Package

composer require laravel/socialite

5 Create Google API Console Project


5.1 Login into Google Developer Account

If you have Google Developer Account Go to https://console.cloud.google.com/, else you can easily create one directly from the Google Developers Console.

5.2 Create New Project

Create a Project in the Google Developer Console

Create Project

Entering Project information in the following Screen

Project Details

Project successfully created with given information's

Project Created Successfully

5.3 Create Credentials

Now Create the credential by choosing "Credentials" in the side bar, click "Create Credentials" button and choose "OAuth Client ID".

Create Credentials

Now Click "Configure Consent Screen" Button.

Configure Consent Screen

It will redirected to the following screen and choose "External" option then create.

external

5.5 Update App Information

By providing App and Developer Information Complete the form then click "Save and Continue" Button.

App Information

5.6 OAuth Client Created

Now Create the OAuth Client by choosing "Credentials" in the side bar, click "Create Credentials" button and choose "OAuth Client ID".

Create Credentials

It will redirected to the following screen and fill the detail about our app and fill the authorized redirect URIs. This is the URI that we will use to redirect user after they choose their Google account to login to our web. For example here I use http://127.0.0.1:8000/callback/google for the callback URI..

Create Oauth

Now we get the Client ID and the Client Secret.

Oauth Successfully

6 Configure Google App Credentials

6.1 Add the Google API Credentials in .env

Insert the Client ID and Client Secret key and redirect URI into the .env file, Which we obtained from previous step GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET. Additionally, include a new key in the .env file called GOOGLE_REDIRECT_URI and populate it with the callback URI used in the Google API Console.

GOOGLE_CLIENT_ID=Your Client ID
GOOGLE_CLIENT_SECRET=Your Client Secret
GOOGLE_REDIRECT_URI=http://127.0.0.1:8000/callback/google

6.2 Add the Google API .env key in config/services.php

Open the config/services.php file and Insert the Google OAuth Credentials

<?php

return [

    // Other services ..
    
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
];
?>
    

6.3 Add New Column within the Users Table to Store google_id

Create a Laravel Migration to Add a New Column within the Users Table to Store google_id

php artisan make:migration add_google_id_to_users

In the generated new migration file, update the up and down methods as described below:

database/migrations/2024_03_27_110820_add_google_id_to_users.php


<?php

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

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

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

Use the following command to run the migration to update your database.

php artisan migrate

6.4 Update the User Model

In your User model , Include google_id in the fillable array of the User Model.
app/Models/User.php

<?php
namespace App\Models;

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

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

?>

7 Create New Controller - GoogleLoginController

Now create a controller "GoogleSocialiteController" and add redirectToGoogle() and handleGoogleCallback() methods
Use the following artisan command to Create Controller.

php artisan make:controller GoogleSocialiteController

app/Http/Controllers/GoogleLoginController.php

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Auth;
use Exception;
use Socialite;

class GoogleSocialiteController extends Controller
{
    public function redirectToGoogle()
    {
        // redirect user to "login with Google account" page
        return Socialite::driver('google')----->redirect();
    }

    public function handleCallback()
    {
        try {
            // get user data from Google
            $user = Socialite::driver('google')->user();
//dd($user);
            // find user in the database where the social id is the same with the id provided by Google
            $finduser = User::where('google_id', $user->id)->first();

            if ($finduser)  // if user found then do this
            {
                // Log the user in
                Auth::login($finduser);

                // redirect user to dashboard page
                return redirect('/dashboard');
            }
            else
            {
                // if user not found then this is the first time he/she try to login with Google account
                // create user data with their Google account data
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id' => $user->id,
                    'password' => bcrypt('my-google'),  // fill password by whatever pattern you choose
                ]);

                Auth::login($newUser);

                return redirect('/dashboard');
            }

        }
        catch (Exception $e)
        {
            dd($e->getMessage());
        }
    }
}
?>

8 Define a Route for Socialite Login with Google

Define routes for the GoogleSocialiteController in the web.php file
routes/web.php

Route::get('auth/google', [GoogleSocialiteController::class, 'redirectToGoogle']);  // redirect to google login
Route::get('callback/google', [GoogleSocialiteController::class, 'handleCallback']);    // callback route after google account chosen

9 Update Login Blade File With Google Button

Create the Link in the login view to Show Google Sign-in Button
resources/views/auth/login.blade.php


<a href="{{ url('auth/google') }}">
 <img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png">
</a>


10 Folder Structure

11 Run Laravel Server to Test the App

Use the following artisan command to Test the App.

php artisan serve

12 Conclusion

That’s all we need to do.
Now the Google Sign-In Implementation completed in Laravel application with the help of Laravel Socialite and breeze package.

Tags