1 Answer

answered by

inchirags@gmail.com  Chirag's Laravel Tutorial https://www.chirags.in
*********************************************************************************************
Laravel 11 Socialite Login with Google Account

*********************************************************************************************

YouTube Video:


 

Step 1: Create laravel 11 using the below command.

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

Step 2: Install Laravel UI Package
Run the following command to install Laravel UI:

composer require laravel/ui

Step 3: Generate Authentication Scaffolding
Laravel UI provides frontend scaffolding with Vue, React, or Bootstrap. For this example, we'll use Bootstrap.
To install the authentication UI with Bootstrap, run:

php artisan ui bootstrap --auth

Step 4: Install Node Modules and Compile Assets
After generating the UI scaffolding, install the necessary frontend dependencies and compile the assets:
Install Node.js dependencies:

npm install

Compile the assets:

npm run dev

If you're in a production environment, use:

npm run build

Step 5: Install Laravel Socialite
Run the following command to install Laravel Socialite in your Laravel 11 project:

composer require laravel/socialite

Step 6: Configure Google API
Visit the Google Cloud Console.

https://console.developers.google.com/

Create a new project or select an existing one.

Go to Credentials > CREATE CREDENTIALS > OAuth client ID.
Choose Web Application and provide a name.
Add the following URLs:
Authorized JavaScript orgins
URIs :

http://localhost:8000

Authorized redirect URIs:

http://localhost:8000/auth/google/callback

Replace localhost:8000 with your actual domain for testing.
Copy the Client ID and Client Secret for use in your Laravel project.
Step 7: Update the .env File
Add the following lines to your .env file:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://localhost:8000/auth/google/callback

Replace your-google-client-id, your-google-client-secret, and your-domain.com with the actual values.
Step 8: Add Socialite Configuration in config/services.php
Edit the config/services.php file and add the Google configuration:

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

Step 9: Define Route
Now, create a new route for laravel socialite.
routes/web.php

use App\Http\Controllers\GoogleController;

Route::controller(GoogleController::class)->group(function(){
    Route::get('auth/google', 'redirectToGoogle')->name('auth.google');
    Route::get('auth/google/callback', 'handleGoogleCallback');
});

Step 10: Create the Socialite Controller
Run the following command to generate a new controller:

php artisan make:controller GoogleController

Update the generated GoogleController:
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,
                    		'avatar' => $user->getAvatar(),
                        	'password' => bcrypt('admin@123')
                    	]
		);
         
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            return redirect('/login')->withErrors(['error' => 'Something went wrong']);
        }
        }
    }
}

Step 11: Update database configuration in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_11_googlelogin
DB_USERNAME=root
DB_PASSWORD=admin@123

Step 12: Update the User Model
1. Add the google_id and avatar column to the users table:

Create a migration:

php artisan make:migration add_google_id_to_users_table

2. Update the migration file:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('google_id')->nullable()->unique();
        $table->string('avatar')->nullable();
    });
}
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn(['google_id', 'avatar']);
    });
}

3. Run the migration:

php artisan migrate

4. Add the below code to the User model.

<?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',
	'avatar'
    ];

    /**
     * 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 13: Create a Login View

Design your login view (resources/views/auth/login.blade.php) with a "Login with Google" button (before <form> closing tag):

@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 14: Test the Implementation

Start the Laravel development server:

php artisan serve

Navigate to 

http://127.0.0.1:8000/login

and click on the Login with Google button.

After successful authentication, you should be redirected to /home.

For any doubts and query, please write on YouTube video comments section.

Note : Flow the Process shown in video.

Please, Subscribe and like for more videos:

https://www.youtube.com/@chiragstutorial

Don't forget to, Follow, Like, Share &, Comment

Thanks & Regards,

Chitt Ranjan Mahto "Chirag"
_____________________________________________________________________
Note: All scripts used in this demo will be available in our website.
Link will be available in description.

Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...