Loading...
+880 1736 699819 Mon - Sat: 9:00 AM - 8:00 PM
Follow us:
Home Blog Article
Blog

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()),
                ])
            );
        }
    }
}

Tags: Blog
Share this post

Encoderbase Team

Author

Articles and insights from the Encoderbase editorial team covering web development, software engineering, and digital solutions.

Enjoyed this article?

Get more articles like this delivered to your inbox — no spam, unsubscribe any time.

Link copied to clipboard!