How to Implement Google Login in Laravel 12
In this tutorial, you'll learn how to integrate Google OAuth login into a Laravel 12 application using Laravel Socialite. This enhances user experience by allowing secure login without passwords.
Prerequisites
- Laravel 12 installed
- Composer
- Basic Laravel knowledge
Step 1: Install Laravel Socialite
composer require laravel/socialite
Step 2: Configure Google API Credentials
- Visit Google Cloud Console
- Create a project
- Navigate to APIs & Services > Credentials
- Create OAuth 2.0 client ID
- Set redirect URI:
http://localhost:8000/auth/google/callback
Step 3: Add to .env
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REDIRECT_URI=http://localhost:8000/auth/google/callback
Step 4: Add to config/services.php
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
Step 5: Add Routes
Route::get('auth/google', [GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
Step 6: Create GoogleController
php artisan make:controller GoogleController
Step 7: Google Login Logic
public function handleGoogleCallback()
{
if (request()->has('error') || !request()->has('code')) {
return redirect('/login')->with('error', 'Google login cancelled.');
}
$googleUser = Socialite::driver('google')->stateless()->user();
$user = User::updateOrCreate(
['email' => $googleUser->getEmail()],
[
'name' => $googleUser->getName(),
'google_id' => $googleUser->getId(),
'avatar' => $googleUser->getAvatar(),
'password' => bcrypt(Str::random(16)),
]
);
Auth::login($user);
return redirect('/home');
}
Step 8: Add google_id & avatar Columns
php artisan make:migration add_google_id_and_avatar_to_users_table
Edit migration file:
$table->string('google_id')->nullable();
$table->string('avatar')->nullable();
php artisan migrate
Step 9: Google Login Button
<a href="{{ url('auth/google') }}">
<button>Login with Google</button>
</a>
Conclusion
You’ve now implemented Google login in your Laravel 12 app using Socialite. This makes logging in faster, more secure, and user-friendly.