Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Socialite Login with Google Tutorial

Last Updated on May 12, 2024 by

Socialite is a built-in Laravel package that helps users to add social logins like google, facebook, twitter, github etc. to the application.

Let’s create the application in Google Developer, and then install Socialite, and add Google Sign-in to in Laravel 11 with its help:

Step 1: Create Account in Google Developer Console

  1. Go to the Google Developer Console: https://console.developers.google.com/.
  2. Sign in or create an account: If you already have a Google Account, sign in using your credentials. If not, click the “Create Account” button and follow the instructions to create a new Google Account.
  3. Create a new project: In the Developer Console dashboard, click the “Select a Project” dropdown at the top of the page, then click the “+ New Project” button. Enter a name for your project and click “Create”.
  4. Enable the Google API: In the sidebar menu on the left, click “APIs & Services” and then select “Library.” Here, you will find a list of Google APIs that you can enable for your project.
  5. Set up the OAuth consent screen: In the sidebar menu, under “APIs and Services,” click “OAuth consent screen.”
  6. Create OAuth 2.0 credentials: After setting up the OAuth consent screen, go back to the “APIs and Services” menu and click “Credentials.” Then, click the “Create Credential” dropdown and select “OAuth Client ID.” Select the application type (Web Application, Android, iOS, etc.), enter a name for your OAuth client, and specify any required redirect URIs. Click “Create” to generate your OAuth Client ID and Client Secret.

Step 2: Add Google App Credentials to the Config

Edit config/services.php file to add the Google OAuth credentials in it:

<?php

return [

    // Other services ..
    
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
];

Edit .env file and set these values in it:

GOOGLE_CLIENT_ID=YOUR_CLIENT_ID
GOOGLE_CLIENT_SECRET=YOUR_CLIENT_SECRET
GOOGLE_REDIRECT_URI=http://127.0.0.1:8000/login/google/callback

Step 3: Install Laravel UI and Bootstrap Auth

Run the following commands to install laravel ui and bootstrap auth in application:

composer require laravel/ui
php artisan ui bootstrap --auth

Install npm and run npm built for bootstrap auth:

npm install
npm run build

Step 4: Install Socialite

Run the following command to install socialite package for google login:

composer require laravel/socialite

Step 5: Create Migration to Add google_id Column in Table

Run the following command to create migration to adding google_id column in table:

php artisan make:migration add_google_id_column

Edit your migration file from database/migrations folder and, add the google_id column in it:

    public function up(): void
    {
        Schema::table('users', function ($table) {
            $table->string('google_id')->nullable();
        });
    }

Update google_id column in app/Models/User.php file:

<?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: Set Up Routes

Set up google sign in routes in routes/web.php file:

<?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

Run the following command to create a google controller:

php artisan make:controller googleController

Implement some methods in application/controllers/googleController.php file to handle google sign in:

<?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: Add Google Sign-In Button in View File

Add google sign in button in resources/views/auth/login.blade.php file:

@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

Step 9: Test Your Application

Run php artisan serve command to start application server:

php artisan serve

Hit the http://localhost:8000/login url on browser for testing this application.

Leave a Comment