Laravel 11 Socialite Login with Google Account Example

By Hardik Savani September 4, 2024 Category : Laravel

In this tutorial, we will learn laravel 11 login with google account using socialite composer package. we can use with laravel ui, laravel jetstream and laravel breaze for login with gmail account.

As we know, social media becomes more and more popular in the world. Everyone has a social account like Gmail, Facebook, etc. I think also most have Gmail accounts. So if your application has login with social, then it becomes awesome. You get more people to connect with your website because most of the people do not want to fill out the sign-up or sign-in form. If they login with social, then it becomes awesome.

In this example, we will install the Socialite composer package for login with Google. Then we will install Laravel UI for Bootstrap authentication. After that, we will add a login with Google button, allowing users to log in and register using their Gmail accounts. So, let's follow the steps below:

Step for Login with Gmail Account in Laravel 11?

  • Step 1: Install Laravel 11
  • Step 2: Install Laravel UI
  • Step 3: Install Socialite
  • Step 4: Create Google App
  • Step 5: Add google_id Column
  • Step 6: Create Routes
  • Step 7: Create Controller
  • Step 8: Update Blade File
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install Laravel UI

Now, in this step, we need to use Composer command to install Laravel UI, so let's run the below command and install the below library.

composer require laravel/ui

Now, we need to create authentication using the below command. You can create basic login, register, and email verification. We will run the below commands to create Bootstrap auth scaffold:

php artisan ui bootstrap --auth

Now, let's node js package:

npm install

let's run package:

npm run build

Step 3: Install Socialite

In the first step, we will install the Socialite Package, which provides an API to connect with Google accounts. So, first open your terminal and run the below command:

composer require laravel/socialite

Step 4: Create Google App

Go to https://console.cloud.google.com/projectcreate and create a new project.

Now go to https://console.cloud.google.com/apis/credentials/consent and after selecting "External," click on "CREATE" as shown in the following image:

Now fill in the required fields i.e. "App Name", "User Support Email", "Developer Contact Info -> Email Address" and click on "Save and Continue". Again click on "Save and Continue", once again click on "Save and Continue" and finally click on "Back to Dashboard".

Now go to https://console.cloud.google.com/apis/credentials and click on "Create Credentials" then click on "OAuth clientID" in a popup as shown in the following image:

Now select the Application type as "Web Application", Add "Authorized redirect URI", and click on "CREATE" as shown in the following image:

Now copy "Client ID" and "Client Secret" as shown in the image, we will add it on .env file:

Now you have to set app id, secret and call back URL in config file so open config/services.php and set id and secret this way:

config/services.php

return [
    ....

    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT'),
    ],
]

Then you need to add google client id and client secret in .env file:

.env

GOOGLE_CLIENT_ID=XXXXXsvqcn3d.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=XXXXXT6tR1rWpR-Jxy3jkdzs
GOOGLE_REDIRECT=http://localhost:8000/auth/google/callback

Step 5: Add google_id Column

In this step, first, we have to create a migration to add the google_id in your user table. So let's run the below command:

php artisan make:migration add_google_id_column

Migration

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::table('users', function ($table) {
            $table->string('google_id')->nullable();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
          
    }
};

Update mode like this way:

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'google_id'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

Step 6: Create Routes

After adding the `google_id` column, first, we have to add new routes for Google login. So let's add the below route in the `routes.php` file.

routes/web.php


<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\GoogleController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
  
Route::controller(GoogleController::class)->group(function(){
    Route::get('auth/google', 'redirectToGoogle')->name('auth.google');
    Route::get('auth/google/callback', 'handleGoogleCallback');
});

Step 7: Create Controller

After adding the routes, we need to add a method for Google authentication. This method will handle the Google callback URL, etc. First, put the code below in your GoogleController.php file.

app/Http/Controllers/GoogleController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
  
class GoogleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }
          
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGoogleCallback()
    {
        try {
        
            $user = Socialite::driver('google')->user();
            $finduser = User::where('google_id', $user->id)->first();
         
            if($finduser){
         
                Auth::login($finduser);
                return redirect()->intended('home');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'google_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
         
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Step 8: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6 offset-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                    <label class="form-check-label" for="remember">
                                        {{ __('Remember Me') }}
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <br/>
                                <a href="{{ route('auth.google') }}">
                                    <img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png">
                                </a>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/login

Output:

I hope it can help you...

Shares