Laravel Google Login with Socialite & Sanctum

Laravel Google Login with Socialite & Sanctum

Modern users expect fast and hassle-free authentication. Allowing people to sign in with Google not only improves user experience but also increases trust and conversion rates. Laravel makes this process simple and secure by combining Socialite with Sanctum.

In this guide, we’ll walk through how Google login works in a Laravel API-based application and how it connects smoothly with a frontend framework like Vue 3 or React.

.env

FRONTEND_URL=http://localhost:3000

Production

FRONTEND_URL=https://hausly.scfnaogaon.org

Staging

FRONTEND_URL=https://staging.hausly.com

config/app.php

'frontend_url' => env('FRONTEND_URL', 'http://localhost:3000'),

FULL Google Login Controller

<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Facades\Socialite;

class GoogleLoginController extends Controller
{
    /**
     * Redirect user to Google OAuth
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')
            ->stateless()
            ->redirect();
    }

    /**
     * Handle Google OAuth callback
     */
    public function handleGoogleCallback()
    {
        DB::beginTransaction();

        try {
            $googleUser = Socialite::driver('google')
                ->stateless()
                ->user();

            $user = User::where('email', $googleUser->getEmail())->first();

            if (!$user) {
                $user = User::create([
                    'name'      => $googleUser->getName(),
                    'email'     => $googleUser->getEmail(),
                    'google_id' => $googleUser->getId(),
                    'password'  => Hash::make(str()->random(16)),
                    'user_type' => 3,
                ]);
            }

            $token = $user->createToken($user->email)->plainTextToken;

            DB::commit();

            // FRONTEND CALLBACK URL (ENV BASED)
            $frontendCallbackUrl = config('app.frontend_url', 'http://localhost:3000')
                . '/auth/google-callback';

            return redirect()->to(
                $frontendCallbackUrl . '?' . http_build_query([
                    'token'   => $token,
                    'user'    => urlencode(json_encode($user)),
                    'status'  => 'success',
                    'message' => urlencode('Registration Success'),
                ])
            );

        } catch (\Exception $e) {

            DB::rollBack();

            $frontendCallbackUrl = config('app.frontend_url', 'http://localhost:3000')
                . '/auth/google-callback';

            return redirect()->to(
                $frontendCallbackUrl . '?' . http_build_query([
                    'status'  => 'error',
                    'message' => urlencode('Google login failed: ' . $e->getMessage()),
                ])
            );
        }
    }
}