Laravel 12 – How to Add Google Login Using Socialite and Livewire Auth.
Laravel 12 – How to Add Google Login Using Socialite and Livewire Auth.
In this tutorial we will learn how to add Google Login to Laravel 12 using Socialite and Livewire Auth, giving your app a secure and seamless authentication experience.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide walks you through integrating Google login into a Laravel 12 project using Livewire authentication. You’ll set up a fresh Laravel project, add a google_id column to the users table, and install Laravel Socialite for OAuth authentication. The guide covers configuring Google OAuth credentials, updating environment variables, and creating a SocialController to handle login and registration. Routes are defined for redirecting users to Google and handling the callback, and a Google login button is added to the Livewire registration page. Finally, you’ll test the setup to ensure users can seamlessly register and log in with their Google accounts.
Step # 1 : Create a Fresh Laravel 12 project with Livewire Auth.
Begin by creating a new Laravel 12 project. If you already have the Laravel Installer installed globally, run.
laravel new google
If you don’t have the Installer, you can create the project using Composer.
composer create-project laravel/laravel --prefer-dist google
Using Composer will set up the project automatically without any interactive questions, so you’ll need to configure authentication, testing, and frontend tools manually later. If you use the Laravel Installer, you will go through a short guided setup. Choose the following options when prompted.
- Starter Kit: Select Livewire, which sets up Livewire-based authentication.
- Authentication Provider: Choose Laravel's built-in authentication for a simple default setup.
- Laravel Volt: Select No, since this project doesn’t require Volt.
- Testing Framework: Choose Pest, a clean and modern testing framework.
- Frontend Dependencies: Select Yes to automatically install all required frontend packages.
Once these options are selected, Laravel will generate a fresh project using Livewire authentication, Pest for testing, SQLite as the default database, and all default migrations already included.
Step # 2 : Navigate to Your Project Directory.
Open your terminal (Git Bash, CMD, or PowerShell) and move into the root folder of your Laravel project.
cd c:xampp/htdocs/google
This confirms you're inside the correct project location before proceeding further.
Step # 3 : Update the Users Table and User Model.
To support Google login, start by modifying the users table. Open the create_users_table migration file and add a new google_id column.
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('google_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Next, update your User model (app/Models/User.php) by adding google_id to the $fillable array so it can be mass assigned.
protected $fillable = [
'google_id',
'name',
'email',
'password',
];
After updating both the migration and the User model, run the following command to refresh your database and apply the changes since we are using the default SQLite database.
php artisan migrate:fresh
This will reset your database and create all tables, including the new google_id column, preparing it for Google authentication.
Step # 4 : Install Laravel Socialite Package.
To enable social authentication (like Google login), you need to install the Socialite package. Run the following command in your project root.
composer require laravel/socialite
Composer will download and install Socialite along with its dependencies and update your composer.json file automatically.
Step # 5 : Obtain Google App ID and App Secret.
To enable Google login, you need to create a project in the Google Developer Console and get your Client ID and Client Secret. Follow these steps.
- Log in to the Google Developer Console. (Link : https://console.cloud.google.com/cloud-resource-manager)
- Click Create Project.
- Define the Project Name.
- Access your newly created project.
- Navigate to API & Services.
- Then click on OAuth consent screen.
- Then click on Get Started.
- Provide the App information and User support email.
- Select the User Type as External.
- Add the required contact information. For production, complete all necessary details.
- Click on Create OAuth client.
- Select the Application type as Web application and then fill in all the details like name, Authorized JavaScript Origins and Authorized redirect URIs then click on create.
- You'll now see the Client ID and Client Secret. Make sure to save these for future use.
Now, Open config/services.php and add the Google configuration.
//Google Login
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
Open your .env file and add the following variables.
GOOGLE_CLIENT_ID="Define your client ID here"
GOOGLE_CLIENT_SECRET="Define your client SECRET here"
GOOGLE_REDIRECT_URI=http://localhost:8000/auth/google/callback
Make sure the redirect URI matches the one you set in the Google Developer Console. Adjust the port if needed (for example, 8000 when using Laravel's built-in server).
Step # 6 : Create SocialController for Google Login.
Generate a new controller to handle Google authentication.
php artisan make:controller SocialController
Now, update SocialController.php with the following code to manage Google authentication.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Exception;
class SocialController extends Controller
{
public function googleRedirect()
{
return Socialite::driver('google')->redirect();
}
public function loginWithGoogle()
{
try {
// Retrieve user from Google
$googleUser = Socialite::driver('google')->stateless()->user();
// Attempt to find an existing user by Google ID or email
$existingUser = User::where('google_id', $googleUser->id)
->orWhere('email', $googleUser->email)
->first();
if ($existingUser) {
// Update Google ID if the user was found by email
if ($existingUser->google_id !== $googleUser->id) {
$existingUser->google_id = $googleUser->id;
$existingUser->save();
}
Auth::login($existingUser);
} else {
// Create a new user
$createUser = User::create([
'name' => $googleUser->name,
'email' => $googleUser->email,
'google_id' => $googleUser->id,
// Hashing the password
'password' => bcrypt('password'),
]);
Auth::login($createUser);
}
return redirect()->to('/dashboard'); // Direct path to your dashboard
} catch (\Throwable $th) {
// Log the exception or handle it as needed
throw $th; // Consider logging the exception for debugging
}
}
}
This controller handles Google authentication using Livewire conventions. It redirects users to Google’s login page, then processes the callback to either log in existing users or create new ones with a secure random password. If a user already exists, their google_id is updated if missing. After successful authentication, users are redirected to the dashboard. Any errors during the process are logged and a friendly message is displayed, ensuring a smooth login experience.
Step # 7 : Set Up Routes for Google Authentication.
First, import the SocialController at the top of your routes/web.php file.
use App\Http\Controllers\SocialController;
Next, define the routes for Google login.
// Route to redirect users to Google for authentication
Route::get('auth/google', [SocialController::class, 'googleRedirect']);
// Route to handle the callback from Google after authentication
Route::get('auth/google/callback', [SocialController::class, 'loginWithGoogle']);
These routes handle the full Google authentication flow. The first route sends users to Google’s login page, and the second route processes the callback to log in or register the user in your Laravel application.
Step # 8 : Add Google Login Button to Your Registration/Login Page.
To enable Google login in your Livewire based registration form, add the following snippet right after the registration button in your Blade view.
<!-- Separator OR section -->
<div class="text-center">
<span class="text-sm text-gray-600">OR</span>
</div>
<!-- Login with Google button -->
<div class="flex items-center justify-center">
<a href="{{ url('auth/google') }}"
class="inline-block w-full text-center px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-lg text-gray-800 font-semibold">
Login with Google
</a>
</div>
This will display a Google login button below the standard registration form. Clicking it will redirect users to Google for authentication.
Step # 9 : Test Google Login.
Now it’s time to make sure everything works as expected. Start the Laravel development server.
php artisan serve
Once the server is running, navigate to the Register page. You should now be able to register using a Google email.
Conclusion
By following this guide, you’ve successfully integrated Google login into your Laravel 12 project using Livewire authentication, allowing users to register or log in seamlessly with their Google accounts. Laravel Socialite handles the OAuth process securely and efficiently, while your database stores the relevant user information, including the Google ID. This setup provides a convenient, modern authentication option and can be further customized with additional social providers, role-based access, or tailored login flows to fit your application’s needs.
For more details, refer to the Laravel Socialite documentation
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments