How to Implement Google Login Using Gmail in Laravel

How to Implement Google Login Using Gmail in Laravel

Google login is a powerful feature that allows users to sign in using their Gmail account, improving user experience and reducing friction during registration. In this tutorial, we will guide you through the Google login integration process in a Laravel application.

Why Use Google Login in Laravel?

  • Enhanced User Experience: Users can sign in with one click.
  • Security: OAuth 2.0 ensures a secure authentication process.
  • Reduce Fake Accounts: Google verifies users' identities.


Prerequisites

Before starting, ensure you have:

  • Laravel 11 installed
  • Composer


Step 1: Install Socialite Package

composer require laravel/socialite

Also install

composer require guzzlehttp/guzzle


Step 2: Configure Google Credentials

  • Create a new project and enable "Google Identity".
  • Set up OAuth consent screen and add your domain.
  • Create new credentials for OAuth Client ID:


Step 3: Add Credentials to .env


GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URI=http://yourdomain.com/auth/google/callback


Step 4: Configure Socialite in config/services.php


return [
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
];


Step 5: Add Google ID Column to Users Table


Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
$table->string('google_id', 100)->nullable();
            $table->string('email')->unique();
            $table->string('phone')->nullable()->unique();
            $table->string('avatar')->nullable();
            $table->string('role', 20)->nullable();
            $table->string('status')->nullable(false);
            $table->string('username')->unique();
            $table->timestamps();
       });

Run the migration:

php artisan migrate


Step 6: Create Google Controller

php artisan make:controller Auth/GoogleController


Step 7: Set Up Routes


use App\Http\Controllers\Auth\GoogleController;

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


Add the following code to the controller:

   
<?php

    namespace App\Http\Controllers\Auth;

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

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

        public function handleGoogleCallback()
        {
            try {
                $userData = Socialite::driver('google')
                    ->setHttpClient(new \GuzzleHttp\Client(['verify' => false]))
                    ->stateless()
                    ->user();

                $user = User::where('email', $userData->email)->first();
                if ($user) {
                    // Update Google ID if not set
                    if (!$user->google_id) {
                        $user->update([
                            'google_id' => $userData->id,
                            'avatar'    => $userData->avatar,
                        ]);
                    }

                    Auth::login($user);
                   
                    if ($user->role === 'User') {
                        return redirect()->route('frontend.dashboard')->with('success', 'Login successful.');
                    } else {
                        Auth::logout();
                        return redirect()->route('frontend.login')->with('error', 'Access denied.');
                    }
                }
               
                $username = $this->generateUniqueUsername($userData->email);

                // Create a new user if not exists
                $newUser = User::create([
                    'google_id'          => $userData->id,
                    'name'               => $userData->name,
                    'email'              => $userData->email,
                    'username'           => $username,
                    'avatar'             => $userData->avatar,
                    'status'             => true,
                    'role'               => 'User',
                ]);

                Auth::login($newUser);

                return redirect()->route('frontend.dashboard');

            } catch (Exception $e) {
                return redirect()->route('frontend.login')->with('error', 'Something went wrong. Please try again.');
            }
        }

        function generateUniqueUsername($email)
        {
            // Extract username from email
            $username = Str::slug(explode('@', $email)[0]);

            // Ensure username is at least 3 characters long
            if (strlen($username) < 3) {
                $username .= rand(100, 999);
            }

            // Check if username exists and make it unique
            $originalUsername = $username;
            $count = 1;

            while (User::where('username', $username)->exists()) {
                $username = $originalUsername . $count;
                $count++;
            }

            return $username;
        }
    }


Step 8: Run The Server

php artisan serve


Comments