Laravel 9 - Login with Google using Socialite

Touseef Afridi
28 Aug 24

Laravel 9 - Login with Google using Socialite

In this tutorial, we will discuss how to use the Socialite package to log in with Google in Laravel 9. Socialite is a package that simplifies OAuth authentication with popular social media platforms like Facebook, Google, and GitHub, allowing users to log in via these platforms while handling the authentication process seamlessly.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This tutorial walks you through integrating Google login into a Laravel project using the Socialite package. After creating the project and setting up the database, you’ll install authentication scaffolding and Socialite, configure Google API credentials, and implement a controller to handle the authentication flow. Finally, you’ll add a Google login button to your Login/Register view and test the functionality. With this implementation, your Laravel application will allow users to authenticate using their Google accounts, making it easier for them to log in without needing to create a new account.

Step # 1 : Create Fresh Laravel Project.

Create a fresh Laravel project named google using the global Laravel installer command.
laravel new google
Or use
If the Laravel installer is not globally installed, use Composer to create the project named google
composer create-project laravel/laravel --prefer-dist google

Step # 2 : Create a Database.

Create a new database named google in your database management tool (phpMyAdmin). Then, update the .env file in your Laravel project with the database connection details.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=google
DB_USERNAME="your database username"
DB_PASSWORD="your database password"

Step # 3 : Let's install UI authentication.

Install the Laravel UI package to enable authentication scaffolding, generate the UI with Vue.js, and install the required NPM dependencies. Finally, compile the frontend assets using Laravel Mix.
composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev

Step # 4 : Add field to users table.

Update the create_users_table migration to add a new google_id field to store Google user IDs. Make google_id fillable in the User model and run the migration to apply the changes.
$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();
Assign google_id as fillable property.
    protected $fillable = [
        'google_id',
        'name',
        'email',
        'password',
    ];
Run the migration to apply the changes and create the google_id field in the users table.
php artisan migrate

Step # 5 : Install Socialite package.

Install the Socialite package to integrate social authentication (Google login) into your Laravel project.
composer require laravel/socialite

Step # 6 : Register socialite package (Optional)

Optionally, register the Socialite package in the config/app.php file by adding it to the providers and aliases arrays.
'providers' => [
    Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

Step # 7 : Get google client_id, client_secret and assign app_url at Google Dev console.

Log in to the Google Developer Console to obtain your Google client ID, client secret, and assign your app's URL. Then, update the config/services.php file with your credentials for Google authentication.

Access config/services.
 'google' => [
        'client_id' => 'google app id',
        'client_secret' => 'google add secret',
        'redirect' => 'http://localhost:8080/auth/google/callback', //Your redirect call back. In my case i am using port 8080. If you are using port 8000 or if you are not using any port you need to update url accordingly
    ],

Step # 8 : Create SocialController.

Create a new controller named SocialController using the following command.
php artisan make:controller SocialController
Then, update the controller with the necessary methods to handle Google authentication.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Validator;
use Socialite;
use Exception;
use Auth;
class SocialController extends Controller
{
    public function googleRedirect()
    {
        return Socialite::driver('google')->redirect();
    }
    public function loginWithGoogle()
    {
        try {
            $user = Socialite::driver('google')->stateless()->user();
            $existingUser = User::where('google_id', $user->id)->first();
            if($existingUser){
                Auth::login($existingUser);
                return redirect('/home');
            }else{
                $createUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id' => $user->id,
                    'password' => encrypt('admin@123')
                ]);
                Auth::login($createUser);
                return redirect('/home');
            }
        } catch (\Throwable $th) {
          throw $th;
       }
    }
}

Step # 9 : Setup routes.

Add routes for Google authentication in the routes/web.php file.
Route::get('auth/google', 'App\Http\Controllers\SocialController@googleRedirect');
Route::get('auth/google/callback', 'App\Http\Controllers\SocialController@loginWithGoogle');

Step # 10 : Add Google login href to your Login/Register blade.

Place the Google login button in the appropriate section of your Login/Register blade file.
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end"></label>
<div class="col-md-6">
<a class="btn btn-primary" href="{{ url('auth/google') }}"> Login with Google</a>
</div>
</div>

Step # 11 : Test the implementation.

Start the Laravel development server and visit the Login/Register page to test the Google login functionality.
php artisan serve
You should now be able to log in using your Google account.


Conclusion

By following these steps, you’ve successfully integrated Google login into your Laravel project, enhancing user experience and simplifying the login process. This setup ensures a smooth authentication flow and prepares your application for social logins, making it more modern and user-friendly.

Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering