Laravel 10/9 Socialite Login with Google Gmail Account

Login with Google gmail account in Laravel 10/9 using socialite and jetstream; Through this tutorial, i am going to show you how to implement Google social login using socialite and jetstream in Laravel 10/9.

In this post, you will learn how implement login with Google in Laravel 10/9. So, i will guide you step by step to implement Google login in Laravel 10/9.

Laravel 10/9 Socialite Login with Google Gmail Account

Use the below given steps to implement google gmail account login using socialite package in Laravel 10/9 apps:

  • Step 1 – Installing Laravel 10/9 App
  • Step 2 – Configuring Database in .env File
  • Step 3 – Installing Socialite
  • Step 4 – Installing Jetstream Auth
  • Step 5 – Add Column in Table
  • Step 6 – Make Google App
  • Step 7 – Create Routes
  • Step 8 – Creating Google Auth Controller
  • Step 9 – Create Google Login Button
  • Step 10 – Start Development Server

Step 1 – Installing Laravel 10/9 App

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

composer create-project --prefer-dist laravel/laravel LaraGoogleLoginApp

Step 2 – Configuring Database in .env File

In step 2, open your downloaded Laravel 10/9 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Installing Socialite

In step 3, Navigate to your downloaded LaraGoogleLoginApp directory. And then install socialite Packages in your laravel apps. Open terminal and run the following command:

cd / LaraGoogleLoginApp

composer require laravel/socialite

Then configure this package in app.php file, which is located inside config directory.

Add the ServiceProvider in config/app.php:

'providers' => [
    /*
     * Package Service Providers...
     */
    Laravel\Socialite\SocialiteServiceProvider::class,
]

Then add the Facade in config/app.php:

'aliases' => [
    ...
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
]

Step 4 – Installing Jetstream Auth

In step 4, install jetstream laravel auth scaffolding. You can read this Laravel 10/9 AUTH TUTORIAL: LOGIN/REGISTER/PASSWORD RESET EXAMPLE.

Step 5 – Add Column in Table

In step 5, add social login column in database table. Open command prompt and type the following command:

php artisan make:migration add_social_login_column

Then open add_social_login_column.php file, which is located inside database/migration directory. And add the following code into it:

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

Also, add the following code into User.php model, which is located inside app/Models/ directory:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

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

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 6 – Make Google App

In step 6, click on this https://console.developers.google.com/ url. And when you click, you will look like the google console dahsboard:

After that, click on Credentials and choose first option oAuth and click Create new Client ID button. now you can see following slide:

Then

Then add google app client id, secret and callback url in services.php, which is located inside config directory:

	return [
    ....
    'google' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://localhost:8000/auth/google/callback',
    ],
]

Step 7 – Create Routes

In step 7, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\SocialGoogleController;


Route::get('auth/google', [SocialGoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [SocialGoogleController::class, 'handleCallback']);

Step 8 – Creating Google Auth Controller

In step 8, create google social login controller by using the following command:

php artisan make:controller SocialGoogleController

The above command will create SocialGoogleController.php file, which is located inside LaraGoogleLoginApp/app/Http/Controllers/ directory. So add the following code into it:

<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\Models\User;
  
class SocialGoogleController 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 handleCallback()
    {
        try {
    
            $user = Socialite::driver('google')->user();
     
            $finduser = User::where('social_id', $user->id)->first();
     
            if($finduser){
     
                Auth::login($finduser);
    
                return redirect('/home');
     
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'social_id'=> $user->id,
                    'social_type'=> 'google',
                    'password' => encrypt('google123456')
                ]);
    
                Auth::login($newUser);
     
                return redirect('/home');
            }
    
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Step 9 – Create Google Login Button

In step 9, create google login button in login.blade.php file. So, open login.blade.php, which is located inside resources/views/auth/ directory. And then add the following code into it:

<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label value="{{ __('Email') }}" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label value="{{ __('Password') }}" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <input type="checkbox" class="form-checkbox" name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Login') }}
                </x-jet-button>

                <a href="{{ url('auth/google') }}" style="margin-top: 0px !important;background: green;color: #ffffff;padding: 5px;border-radius:7px;" class="ml-2">
                  <strong>Google Login</strong>
                </a> 
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Step 10 – Start Development Server

In step 10, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/login

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *