How to Implement Google Login in Laravel

Google Login allows users to authenticate with your Laravel application using their Google accounts. This simplifies the login process and enhances security by reducing the need for traditional passwords. Prerequisites Laravel installed (version 8+ recommended) Composer installed A Google Developer account Step 1: Set Up Google OAuth Credentials Go to the Google Cloud Console. Create a new project or select an existing one. Navigate to APIs & Services > Credentials. Click on Create Credentials > OAuth Client ID. Select Web application as the application type. In "Authorized Redirect URIs," add: http://127.0.0.1:8000/auth/google/callback Click Create, then copy the Client ID and Client Secret. Step 2: Install Laravel Socialite Socialite is Laravel's official package for handling OAuth authentication. Run this command to install it: composer require laravel/socialite Step 3: Configure Google OAuth in Laravel Add your Google credentials to the .env file: GOOGLE_CLIENT_ID=your-google-client-id GOOGLE_CLIENT_SECRET=your-google-client-secret GOOGLE_REDIRECT_URI=http://127.0.0.1:8000/auth/google/callback Then, add the Socialite configuration in config/services.php: return [ 'google' => [ 'client_id' => env('GOOGLE_CLIENT_ID'), 'client_secret' => env('GOOGLE_CLIENT_SECRET'), 'redirect' => env('GOOGLE_REDIRECT_URI'), ], ]; Step 4: Create Routes for Google Login Add these routes in routes/web.php: use App\Http\Controllers\GoogleController; Route::get('/auth/google', [GoogleController::class, 'redirectToGoogle'])->name('google.login'); Route::get('/auth/google/callback', [GoogleController::class, 'handleGoogleCallback']); Step 5: Create Google Authentication Controller Run the following command to generate the controller: php artisan make:controller GoogleController Then, update app/Http/Controllers/GoogleController.php: namespace App\Http\Controllers; use Exception; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Laravel\Socialite\Facades\Socialite; class GoogleController extends Controller { public function redirectToGoogle() { return Socialite::driver('google')->redirect(); } public function handleGoogleCallback() { try { $googleUser = Socialite::driver('google')->user(); // Check if a user with this email exists $user = User::where('email', $googleUser->email)->first(); if (!$user) { // Create a new user if not found $user = User::create([ 'first_name' => $googleUser->name, 'email' => $googleUser->email, 'google_id' => $googleUser->id, 'password' => bcrypt(uniqid()), // Random hashed password ]); } // Log in the user Auth::login($user); return redirect()->route('dashboard')->with('success', 'Login successful!'); } catch (Exception $e) { return redirect()->route('login')->with('error', 'Something went wrong: ' . $e->getMessage()); } } } Step 6: Add Google Login Button to Your View In your login page view (resources/views/auth/login.blade.php), add the Google login button: Login with Google Step 7: Test the Integration Start your Laravel development server: php artisan serve Open http://127.0.0.1:8000/login and click "Login with Google." Sign in with your Google account. If everything is set up correctly, the user will be logged in and redirected to the dashboard. Conclusion You have successfully implemented Google login in your Laravel application using Socialite. This method enhances security and improves user experience by allowing authentication without requiring passwords.

Apr 1, 2025 - 17:16
 0
How to Implement Google Login in Laravel

Google Login allows users to authenticate with your Laravel application using their Google accounts. This simplifies the login process and enhances security by reducing the need for traditional passwords.

Prerequisites

Step 1: Set Up Google OAuth Credentials

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Navigate to APIs & Services > Credentials.
  4. Click on Create Credentials > OAuth Client ID.
  5. Select Web application as the application type.
  6. In "Authorized Redirect URIs," add:
   http://127.0.0.1:8000/auth/google/callback
  1. Click Create, then copy the Client ID and Client Secret.

Step 2: Install Laravel Socialite

Socialite is Laravel's official package for handling OAuth authentication.

Run this command to install it:

composer require laravel/socialite

Step 3: Configure Google OAuth in Laravel

Add your Google credentials to the .env file:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://127.0.0.1:8000/auth/google/callback

Then, add the Socialite configuration in config/services.php:

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

Step 4: Create Routes for Google Login

Add these routes in routes/web.php:

use App\Http\Controllers\GoogleController;

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

Step 5: Create Google Authentication Controller

Run the following command to generate the controller:

php artisan make:controller GoogleController

Then, update app/Http/Controllers/GoogleController.php:

namespace App\Http\Controllers;

use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

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

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

            // Check if a user with this email exists
            $user = User::where('email', $googleUser->email)->first();

            if (!$user) {
                // Create a new user if not found
                $user = User::create([
                    'first_name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'google_id' => $googleUser->id,
                    'password' => bcrypt(uniqid()), // Random hashed password
                ]);
            }

            // Log in the user
            Auth::login($user);
            return redirect()->route('dashboard')->with('success', 'Login successful!');
        } catch (Exception $e) {
            return redirect()->route('login')->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }
}

Step 6: Add Google Login Button to Your View

In your login page view (resources/views/auth/login.blade.php), add the Google login button:

 href="{{ route('google.login') }}" class="btn btn-danger">Login with Google

Step 7: Test the Integration

  1. Start your Laravel development server:
   php artisan serve
  1. Open http://127.0.0.1:8000/login and click "Login with Google."
  2. Sign in with your Google account.
  3. If everything is set up correctly, the user will be logged in and redirected to the dashboard.

Conclusion

You have successfully implemented Google login in your Laravel application using Socialite. This method enhances security and improves user experience by allowing authentication without requiring passwords.