Laravel 8 Socialite Login with Google Gmail Account

Laravel 8 Socialite Login with Google Gmail Account

Step 1: Install Laravel 8

Create a new Laravel 8 project and navigate to the project folder:

laravel new google_login cd google_login

Step 2: Install Socialite

Install the Socialite package via Composer, which provides the functionality for connecting with Google:

composer require laravel/socialite

Once installed, add the following lines to the config/app.php file to register the provider and alias:

  • Add provider in the providers array:

'providers' => [ ... Laravel\Socialite\SocialiteServiceProvider::class, ],
  • Add alias in the aliases array:

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

Step 3: Create a Google App

  1. Go to Google Developers Console.

  2. Create a new project.

  3. Navigate to Credentials and click Create Credentials, then select OAuth 2.0 Client ID.

  4. Configure the consent screen, then set the application type to Web application.

  5. Add http://localhost:8000 as an authorized JavaScript origin.

  6. Add http://localhost:8000/auth/google/callback as an authorized redirect URI.

  7. Copy the Client ID and Client Secret.

Step 4: Configure the Google API Keys in Laravel

Open config/services.php and add the following configuration for Google:

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

Now, add these values to the .env file:

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

Step 5: Install Laravel UI and Generate Auth Scaffolding

Next, we need to install laravel/ui to generate the authentication scaffolding.

  1. Install Laravel UI:

composer require laravel/ui
  1. Generate the authentication scaffolding:

php artisan ui bootstrap --auth
  1. Install dependencies using NPM:

npm install npm run dev

Step 6: Add Google ID to the User Table

We need to add a google_id column to the users table. Run the following command to generate a migration:

php artisan make:migration add_google_id_to_users_table

Edit the migration file to add the google_id column:

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

Run the migration:

php artisan migrate

Now, update the User model to allow mass assignment for google_id:

// app/Models/User.php protected $fillable = [ 'name', 'email', 'password', 'google_id' ];

Step 7: Define Routes for Google Authentication

In routes/web.php, add the following routes for Google authentication:

Route::get('auth/google', 'App\Http\Controllers\Auth\GoogleController@redirectToGoogle'); Route::get('auth/google/callback', 'App\Http\Controllers\Auth\GoogleController@handleGoogleCallback');

Step 8: Create GoogleController

Create a new controller for handling Google authentication:

php artisan make:controller Auth/GoogleController

In app/Http/Controllers/Auth/GoogleController.php, add the following methods:

namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Socialite; use Auth; use App\Models\User; use Exception; class GoogleController 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()->route('home'); } else { $newUser = User::create([ 'name' => $user->name, 'email' => $user->email, 'google_id' => $user->id, 'password' => encrypt('SuperSecretPassword') // You can update this with a random password or use a secure method ]); Auth::login($newUser); return redirect()->route('home'); } } catch (Exception $e) { dd($e->getMessage()); } } }

Step 9: Update the Login Blade View

In resources/views/auth/login.blade.php,Add a Google login button to the login form:

@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 <!-- Add your email and password fields here --> <div class="form-group row mb-0"> <div class="col-md-8 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('Login') }} </button> <a href="{{ url('auth/google') }}" class="btn btn-lg btn-success btn-block mt-3"> <strong>Login With Google</strong> </a> </div> </div> </form> </div> </div> </div> </div> </div> @endsection

Step 10: Run the Application

Now that everything is set up, start your Laravel development server:

php artisan serve

Visit http://localhost:8000/login, and you should see a "Login With Google" button on your login page. Clicking it will redirect you to Google, and once you authenticate, you’ll be logged into your Laravel application.

That's it! You've now integrated Google login in your Laravel 8 application using Socialite. If you have any further questions or need additional functionality, feel free to ask!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close