How to Implement "Login with Google" in Laravel 11

johnmaths9

John Maths

Posted on August 17, 2024

How to Implement "Login with Google" in Laravel 11

Prerequisites

  • Laravel project set up
  • Composer installed
  • Google Developer Account

Step 1: Set up Google OAuth Credentials

  1. Go to the Google Developer Console
  2. Create a new project or select an existing one
  3. Enable the Google+ API
  4. Go to Credentials -> Create Credentials -> OAuth Client ID
  5. Select Web Application, add your app's URL and callback URL (e.g., http://your-app-url/login/google/callback)
  6. Note down your Client ID and Client Secret

Step 2: Install Laravel Socialite

Install Laravel Socialite via Composer:

composer require laravel/socialite
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Socialite

Add the following to your config/services.php file:

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

Then, add these to your .env file:

GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URI=http://your-app-url/login/google/callback
Enter fullscreen mode Exit fullscreen mode

Step 4: Set up Routes

Add these routes to your routes/web.php:

use App\Http\Controllers\Auth\GoogleController;

Route::get('login/google', [GoogleController::class, 'redirectToGoogle'])->name('login.google');
Route::get('login/google/callback', [GoogleController::class, 'handleGoogleCallback']);
Enter fullscreen mode Exit fullscreen mode

Step 5: Create GoogleController

Create a new controller:

php artisan make:controller Auth/GoogleController
Enter fullscreen mode Exit fullscreen mode

Implement the controller:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

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()->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());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Update User Model

Add google_idto the fillable array in your User model:

protected $fillable = [
    'name',
    'email',
    'password',
    'google_id',
];
Enter fullscreen mode Exit fullscreen mode

Step 7: Add Google ID to Users Table

Create a new migration:

php artisan make:migration add_google_id_to_users_table
Enter fullscreen mode Exit fullscreen mode

In the new migration file:

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

public function down()
{
    Schema::table('users', function ($table) {
        $table->dropColumn('google_id');
    });
}
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 8: Add Login Button

In your login view, add a "Login with Google" button:

<a href="{{ route('login.google') }}" class="btn btn-danger">
    Login with Google
</a>
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
johnmaths9
John Maths

Posted on August 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024