How to implement google login in laravel?

By Shubham G on May 31, 2025

Learn how to seamlessly integrate Google Login into your Laravel application for secure authentication. This guide covers step-by-step implementation, including setting up credentials, configuring OAuth, and handling user authentication efficiently.

Step 1 : Get Credentials

To set up Google login, you'll need a Google Client ID and Client Secret. You can obtain these credentials from the Google Developers Console. http://console.developers.google.com/


On top navbar click on Create Credentials, select the OAuth client ID option.


Select Application Type as Web Application and enter the required details, including Type, Name, and the Redirection and Origin URL (the Origin URL is simply your domain where the project is hosted).


Ensure that you provide the correct redirect URL which serves as the callback URL. Simply use: https://your.domain/google-callback.


After creating the project, you'll receive your Client ID and Secret Key. Be sure to store them securely.

Step 2 : Installing Package

We will be using socialite package of laravel, To install this package run the command below.

composer require laravel/socialite

Step 3 : Update fileds in User Table

Open your user migration file and add the following two fields : 

Social Type : This field ensures that users who registered via Google cannot update their email.

Social ID : A unique identifier provided by Google, used to verify if a user already exists. If a match is found, the login process is executed; otherwise, the registration process is initiated.  

$table->string('social_id')->nullable();
$table->string('social_type')->default('email');

Step 4 : Google Login process with Laravel

Let's create a Google Auth Controller. Run the following command to generate it, and the controller will be created at:  app/Http/Auth/GoogleController.php

php artisan make:controller Auth/GoogleController

Before working on the controller, let's first set up the login/registration button. Since designs vary, we'll primarily focus on the Google button. Open your login.blade.php file and add this button.

<a href="{{route('google.login')}}" class="btn btn-google">
    <span class="fab fa-google"></span> {{ __('Google') }}
</a>

We forgot to add the necessary routesso let's include them now. Open your web.php file and add the following routes.

use App\Http\Controllers\Auth\GoogleController;



// Google Login Routes
Route::get('auth-google', [GoogleController::class, 'redirectToGoogle'])->name('google.login');
Route::get('google-callback', [GoogleController::class, 'handleGoogleCallback'])->name('google.callback');

Now navigate to Auth\GoogleController.php and create a constructor function to dynamically set configuration credentials. You can store your credentials in .env or a database, depending on your system setup and preference.

public function __construct()
{
    $client_id = 'GOOGLE_CLIENT_ID';
    $client_secret = 'GOOGLE_CLIENT_SECRET';
    
    config(
        [
            'services.google.client_id' => $client_id,
            'services.google.client_secret' => $client_secret,
            'services.google.redirect' => route('google.callback'),
        ]
    );
}

Create another function to redirect users to the Google login page (hosted by Google).

use Laravel\Socialite\Facades\Socialite;


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

Create a function to handle the callbackThis function will verify whether the user already exists in the system, If found, it will proceed with the login processotherwise, it will create a new user using the data provided by Google.

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;



public function handleGoogleCallback()
{
    try {
        // Retrieve user details from Google using Socialite
        $user = Socialite::driver('google')->user();

        // Check if the user already exists in the database using their social ID
        $finduser = User::where('social_id', $user->id)->first();

        if ($finduser) {
            // If user exists, log them in and redirect to the home page
            Auth::login($finduser);
            return redirect('/home');
        } else {
            // Extract first and last name from Google's provided full name
            $fullName = explode(' ', $user->name);
            $firstname = $fullName[0];
            $lastname = isset($fullName[1]) ? $fullName[1] : '';

            // Check if the user exists and was previously registered using Google
            if (!empty($finduser->social_type) && $finduser->social_type == 'google') {
                // Update user details with Google's provided data
                $existingUser = [
                    'first_name' => $firstname,
                    'last_name' => $lastname,
                    'email' => $user->email,
                    'social_id' => $user->id,
                    'profile' => $user->avatar,
                ];

                // Update or create a new user record in the database
                User::updateOrCreate(
                    ['email' => $user->email],
                    $existingUser
                );

                // Retrieve the updated user and log them in
                $login_user = User::where('email', $existingUser['email'])->first();
                Auth::login($login_user);
            } else {
                // Create a new user if they do not exist in the database
                $newUser = [
                    'first_name' => $firstname,
                    'last_name' => $lastname,
                    'email' => $user->email,
                    'social_id' => $user->id,
                    'social_type' => 'google',
                    'profile' => $user->avatar,
                    'password' => encrypt('123456789'), // Assigning a default encrypted password
                    'email_verified_at' => Carbon::now()->format('Y-m-d H:i:s') // Mark email as verified
                ];

                // Save the new user record in the database
                User::updateOrCreate(
                    ['email' => $user->email],
                    $newUser
                );

                // Retrieve the newly created user and log them in
                $login_user = User::where('email', $newUser['email'])->first();

                // Log in the newly created user
                Auth::login($login_user);
            }

            // Redirect the user to the home page after successful login or registration
            return redirect('/home');
        }
    } catch (\Exception $e) {
        // Handle any exceptions and redirect back to the login page with an error message
        return redirect()->route('login')->with('error', $e->getMessage());
    }
}

That's a wrap! As we mentioned, It doesn't require separate processes for login and registration, The same function efficiently handles both. Just place the Google button on both the login and registration pages, and the flow will work seamlessly.

Loading...