Laravel 10 Socialite Login With Google Account

In this article, we will see laravel 10 socialite login with a google account. Here, we will learn how to create a socialite login with google in laravel 10. Also, we will see how to socialite login with a google account in laravel 10 using jetstream. You can directly signup with a few steps.

Laravel also provides a simple, convenient way to authenticate with OAuth providers using Laravel Socialite. Socialite currently supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket.

So, let's see login with google in laravel 10, socialite login with google account in laravel 10, login with gmail in laravel 10, and laravel socialite API.

Step 1: Install Laravel 10

In this step, we will install laravel 10 using the below command.

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

 

 

Step 2: Install JetStream

Then, we will install jetstream. So, run the below command to install jetstream.

composer require laravel/jetstream

Now, we need to install livewire using the below artisan command and also we need basic authentication like login and registration otherwise you can install using auth command.

php artisan jetstream:install livewire

Create Auth:

php artisan ui bootstrap --auth

Now, Install Node and run the package.

npm install
npm run dev

 Now, we will create a database using the migration command.

php artisan migrate

 

 

Step 3: Install Socialite

 Now, we will install the socialite package which provides API to connect with a google account. So, run the below command.

composer require laravel/socialite

 

Step 4: Create Google App

Now, we required a google client id and a secret key, if you don't have a google app account then you need to create one from the following link.

Google Account: Google Developers Console

socialite_login_with_google_create_credentials_laravel_10

Create 0Auth client ID as given in the below image.

socialite_login_with_google_create_oauth_client_id_laravel_9

socialite_login_with_google_create_callback_url_laravel_9

After the configuration of the google app, we will set the app id, secret key, and call back URL in the config file. So, add the below code in config/services.php.

'google' => [
        'client_id' => 'your client id',
        'client_secret' => 'your client secret key',
        'redirect' => 'http://localhost:8000/authorized/google/callback',
],

 

 

Step 5: Add Column In User Table

Now, run the below command to add the google id column in the user table. 

php artisan make:migration add_google_id_to_users_table

Create google_id migration and add google_id in the user table.

<?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
    {
          
    }
};

Add the below code to the User model.

<?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 string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'google_id'
    ];
  
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];
  
    /**
     * The attributes that should be cast.
     *
     * @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',
    ];
}

 

 

Step 6: Create Route

Now, we will add a new route for laravel socialite to the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\LoginWithGoogleController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('/', function () {
    return view('welcome');
});
  
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
    return view('dashboard');
})->name('dashboard');
  
Route::controller(LoginWithGoogleController::class)->group(function(){
    Route::get('authorized/google', 'redirectToGoogle')->name('auth.google');
    Route::get('authorized/google/callback', 'handleGoogleCallback');
});

 

Step 7: Create Controller

Then, we will create LoginWithGooglecontroller using the following command.

php artisan make:controller LoginWithGooglecontroller

app/Http/Controllers/LoginWithGooglecontroller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Exception;

class LoginWithGoogleController extends Controller
{
     public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    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('dashboard');
       
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
      
                Auth::login($newUser);
      
                return redirect()->intended('dashboard');
            }
      
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

 

 

Step 8: Edit Login Blade File

Now, edit the login.blade.php file and add the below code to the file.

<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 for="email" value="{{ __('Email') }}" />
                <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

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

            <div class="block mt-4">
                <label for="remember_me" class="flex items-center">
                    <input id="remember_me" 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>
            </div>
            <div class="flex items-center justify-end mt-4">
                <a href="{{ url('authorized/google') }}">
                    <img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png" style="margin-left: 3em;">
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Output:

laravel_9_socialite_login_with_google

 


You might also like :

RECOMMENDED POSTS

FEATURE POSTS