Laravel 11 - How to integrate Google Login
Laravel 11 - How to integrate Google Login
In this tutorial, we’ll cover how to integrate Google login in Laravel 11, simplifying authentication and boosting user experience with social login. Learn the steps to set up Google OAuth for secure, seamless access in your Laravel application.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide covers integrating Google login into a Laravel project with Breeze. It includes setting up Laravel, adding a google_id field to the users table, and installing Laravel Socialite for OAuth authentication. You'll configure Google OAuth credentials, update environment variables, and create a SocialController to handle authentication. Routes are defined for redirection and callback handling, and a Google login button is added to the Blade template. Finally, the guide explains how to test the setup, enabling seamless Google authentication in your Laravel app.
Step # 1 : Create fresh Laravel project with Breeze Auth.
If Laravel is installed globally, run the following command to create a new project.
laravel new google
Or
Alternatively, if Laravel is not installed globally, you can use Composer.
composer create-project laravel/laravel --prefer-dist google
After running one of the above commands, you'll be prompted.
- Would you like to install the starter kit? — Select Breeze
- After selecting Breeze, you'll be asked to choose your stack. — Select Blade.
- After selecting Blade, you'll be asked for dark mode support. — Select no
- After selecting No, you'll be asked about testing framework. — Select Pest
- After selecting Pest, you'll be asked if you want to initialize git repo. — Select no
- After selecting no, you'll be asked to select the database for your application. — Select mysql
- After selecting MySql, you'll be asked if you want to run the default database migration. — Select no
As we will be adding an additional field for google_id.
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to the root folder of your Laravel project.
cd c:xampp/htdocs/google
Step # 3 : Modify the Users Table & User Model.
To accommodate Google login, you'll need to update the users table. Access create_users_table and insert a new column named google_id.
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();
});
In your User model (located at app/Models/User.php), add google_id to the $fillable array to allow mass assignment of the new field.
protected $fillable = [
'google_id',
'name',
'email',
'password',
];
After making these changes, run the migration to update your database.
php artisan migrate
This will add the new google_id column to your users table, along with creating all necessary tables when the migration is executed.
Step # 4 : Install Socialite package.
To enable social authentication, you need to install the Socialite package. Run the following command.
composer require laravel/socialite
After running this command, Composer will download and install the Socialite package along with its dependencies. It will also update the composer.json file in your project to include the Socialite package, ensuring it's ready for use in your Laravel application.
Step # 5 : Obtain Your Google APP_ID and APP_SECRET.
To set up Google login, you need to create a project in the Google Developer Console and obtain your Client ID and Client Secret. Here's how.
Log in to the Google Developer Console. (Link : https://console.cloud.google.com/cloud-resource-manager)
Click Create Project.
Define the Project Name.
Access the Project.
Click on API & Services.
Then click on OAuth consent screen.
Select the user type as External.
Provide the app information, user support email, and developer email. For testing, you can leave other fields blank, but for production, complete all necessary details.
Under Test Users, add any test users. While the app is in Testing mode, only these users can access Google login. Once the app is in production, anyone can use it.
Click on Credentials, then click Create Credentials and select OAuth client ID.
Assign Authorized JavaScript Origins and Authorized redirect URIs, then save the configuration.
You'll now see the Client ID and Client Secret. Make sure to save these for future use.
To set up Google authentication, go to config/services.php and add the following configuration.
//Google Login
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
Open the .env file in your Laravel project and add the following environment 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
Ensure the redirect URL matches the one set in your Google Developer Console. Update the port if needed (e.g., 8000 for Laravel's built-in server) or remove it if unnecessary.
Step # 6 : Create SocialController.
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 manages the Google authentication process by redirecting users to Google's authentication page and handling the authentication response. If a user already exists in the database, they are logged in, and their Google ID is updated if missing. If the user does not exist, a new account is created using their Google profile information. After authentication, the user is redirected to the dashboard. In case of any errors during the process, the controller catches and handles them, ensuring a smooth authentication experience.
Step # 7 : Set Up Routes.
First, import the SocialController class.
use App\Http\Controllers\SocialController;
Next, define the routes for Google authentication, where the first route redirects users to Google for authentication, and the second route handles the callback response from Google after authentication.
// Route to redirect 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']);
Step # 8 : Add Google Login Link to Your Register/Login Blade.
To enable Google login, add the following Blade HTML code right after the register button in your Blade view.
<!-- Register button -->
<!-- Separator OR section -->
<div class="text-center mt-4">
<span class="text-sm text-gray-600">OR</span>
</div>
<!-- Login with Facebook button -->
<div class="flex items-center justify-center mt-4">
<x-secondary-button>
<a href="{{ url('auth/google') }}">
Login with Google
</a>
</x-secondary-button>
</div>
This will display a Google login button alongside the registration option.
Step # 9 : It's time to test.
Let's run the project and access Login/Register page.
php artisan serve
Once the server is running, navigate to the Login/Register page. You should now be able to log in or register using a Google test user email.
Conclusion
By following this guide, you've successfully integrated Google login into your Laravel project with Breeze authentication, allowing users to register and log in seamlessly using their Google accounts. With Socialite handling authentication, your application now offers a convenient and secure login option. You can further customize the integration to suit your needs.
For more details, check 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