Laravel 9 Socialite Login with Google Example

Laravel 9 Socialite Login with Google Example

Hello friends, Today we will show Laravel 9 Socialite Login with Google Example. In this example i will explain to you how to login with google in Laravel. Here you will learn laravel 9 login with google using socialite package. Sometimes we need to get real user data then we use login with social media like google, facebook, twitter, linkedin etc.

Here, we will provide to you simple example of Laravel 9 Socialite Login with Google Account Example, Laravel 9 login with Gmail, Login with google account in laravel 9.

Laravel 9 Socialite Login with Google Account Example

Step 1: Install Laravel 9

composer create-project laravel/laravel example-app

Step 2: Install JetStream

Now, we required to use composer command to install jetstream, so let’s run the following command and install following library.

composer require laravel/jetstream

Now, let’s node js package:

npm install

let’s run package:

npm run dev

Now, we required to run migration command to create database table.

php artisan migrate

Step 3: Install Socialite

Now we will install Socialite Package that provide api to connect with google account. So, first open your terminal and run following  command.

composer require laravel/socialite

Step 4: Create Google App

Here we required google client id and secret that way we can get information of other user. so if you don’t have google app account then you can create from here : Google Developers Console. you can find following screen :

Read Also :  Laravel Carbon Get Next Month Example

laravel login google

Now you have to click on Credentials and choose first option oAuth and click Create new Client ID button. After you can see bellow slide:

 

After create account you can copy your client id and secret.

Here you will 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' => 'http://localhost:8000/auth/google/callback',
    ],
]

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

.env

GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret

Step 5: Add Database Column

Now, we have to create migration for add google_id in your user table. So let’s run following 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()
    {
        Schema::table('users', function ($table) {
            $table->string('google_id')->nullable();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
};

Update mode like this way:

app/Models/User.php

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

Now adding google_id column first we have to add new route for google login. so let’s add following route in routes.php file.

Read Also :  Restore Back Deleted Records in Laravel 8

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\GoogleController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
    return view('dashboard');
})->name('dashboard');
  
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 add route, we required to add method of google auth that method will handle google callback url and etc, first put bellow code on 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('dashboard');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'google_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
         
                Auth::login($newUser);
        
                return redirect()->intended('dashboard');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Step 8: Update Blade File

Here at last we required to add following view so first create new file login.blade.php file and put following code:

resources/views/auth/login.blade.php

<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">
                    <x-jet-checkbox id="remember_me" 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">
                    {{ __('Log in') }}
                </x-jet-button>
            </div>
            <div class="flex items-center justify-end mt-4 align-middle ">
                <a href="{{ route('auth.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>

Now run your laravel app.

php artisan serve

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

http://localhost:8000/login

I hope you understand of login with google account and it can help you…

Read Also :  PayPal Integration in Laravel Example