Laravel 10 Socialite Login with Google Gmail Account

Google Login API allows the user to sign in to the website using their Gmail Google account without signing up on the website. The Google login system definitely helps to increase the number of subscribers on your website.

For Laravel 10 Socialite Google Login tutorial, you can use the Socialite package to allow users to log in with their Google account. Here’s a step-by-step guide on how to implement Google Socialite login in Laravel 10 app.

Steps for Google Authentication Login in Laravel 10

So follow the following steps to implement login with Google in Laravel apps:

  • Step 1: Download Laravel App
  • Step 2: Setup Database
  • Step 3: Install Socialite Package
  • Step 4: Configure Google Credentials in Laravel
  • Step 5: Get Secrets from google
  • Step 6: Install Auth
  • Step 7: Add a Column in users table
  • Step 8: Add Routes
  • Step 9: Create a Controller
  • Step 10: Add Login Button in Blade Files

Install Laravel App

First, create a fresh Laravel 10 application by adding the following command in the terminal.

composer create-project --prefer-dist laravel/laravel laravel-google-login

Next, Go inside the your app

cd laravel-google-login

Setup Database

Now to your project root .env file and set up the database credentials just add DB name, user and database password on it.

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=databasename
 DB_USERNAME=username
 DB_PASSWORD=password

Install Socialite Package

Now install the Laravel Socialite package for Google login. Open the command prompt and run the below command.

composer require laravel/socialite

After successfully installing the Socialite package add allies and providers in config/app.php.

'providers' => [
     // Other service providers…
 Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
// Other aliases…
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

Configure Google Credentials in Laravel

In your config/services.php update the Google credentials using the .env file. After creating the app you must update the details in env just like below.

config/services.php

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

Get Secrets from google

Visit the Google Developers Console (https://console.developers.google.com/), create a new project, and enable the Google+ API. Then, create credentials and obtain the client ID and client secret.

Put the callback url here in google account.

A modal will pop up with your apps client id and client secret. Add these values to your .env file.

.env

GOOGLE_CLIENT_ID=000000000000-XXXXXXXXXXX.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=XXXXXXXXXXXXX
GOOGLE_REDIRECT=http://localhost:8000/callback

Enable Authentication

In this step, we need to install Laravel ui and generate auth in the Laravel application so, let’s run the following command.

Laravel 5 below:

php artisan make:auth

Laravel 6 above:

//install laravel ui
composer require laravel/ui

//create auth
php artisan ui bootstrap --auth

//NPM Install package
npm install
npm run dev

Add Column in the users table

In this step, use the following command to create a migration file for adding column in the database table.

php artisan make:migration add_social_login_field

After that, open the add_social_login_field.php file, which is found 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 AddGoogleIdColumn 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()
    {
        //
    }
}

After successfully adding the field to the database table. Then add a fillable property in the User.php model, which is found inside app/Models/ directory:

protected $fillable = [
         'name', 'email', 'password', 'google_id'
     ];

After that, execute the following command on cmd to create tables in your selected database:

php artisan migrate

Make Routes

In this step, create a route for accessing Laravel login with Google account. So, open and update the routes/web.php file:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\SocialController;
use App\Http\Controllers\HomeController;
 
Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('home', [HomeController::class, 'index'])->name('home');
Route::get('redirect', [SocialController::class, 'redirect'])>name('redirect');
Route::get('callback', [SocialController::class, 'callback'])->name('callback');

Create Controller

Now you need to create a controller by just adding the below command and generating a new resource controller SocialController.

php artisan make:controller SocialController

After running this command you will find a new file in this path “app/Http/Controllers/SocialController.php”. As you saw here already created methods same as below. Now you need to put the below codes on your functions.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response,File;
use Socialite;
use Auth;
use App\User;

class SocialController extends Controller
{

public function redirect()
{
    return Socialite::driver('google')->redirect();
}

public function callback()
{
    try {
            $user = Socialite::driver('google')->user();
            $user = User::where('google_id', $user->id)->first();

            if($user){
                Auth::login($user);
                return redirect('/home');
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
                Auth::login($newUser);
                return redirect('/home');
            }
        } catch (Exception $e) {
            dd($e->getMessage());
        }
   }
}

Add Button in Blade Files

Now add a login button to login blade view and register blade files.

Open the resources/Views/Auth/register.blade.php and add a google social login button.

<hr>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<a href="{{ url('/redirect') }}" class="btn btn-primary"><i class="fa fa-google"></i> Google</a>
</div>
</div>

Same go to Resources/Views/Auth/login.blade.php

<hr>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<a href="{{ url('/redirect') }}" class="btn btn-primary"><i class="fa fa-google"></i> Google</a>
</div>
</div>

Now start the development server using running below command.

php artisan serve

After running this command you can check your browser the Google login is updated in your register and login pages.

http://localhost:8000/login

So the Laravel Socialite Login with Google Gmail Account is completed now.

2 thoughts on “Laravel 10 Socialite Login with Google Gmail Account”

Leave a Comment