DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

2 1 1 1 2

How to Implement Google Login in Laravel

Google Login allows users to authenticate with your Laravel application using their Google accounts. This simplifies the login process and enhances security by reducing the need for traditional passwords.

Prerequisites

Step 1: Set Up Google OAuth Credentials

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Navigate to APIs & Services > Credentials.
  4. Click on Create Credentials > OAuth Client ID.
  5. Select Web application as the application type.
  6. In "Authorized Redirect URIs," add:
   http://127.0.0.1:8000/auth/google/callback
Enter fullscreen mode Exit fullscreen mode
  1. Click Create, then copy the Client ID and Client Secret.

Step 2: Install Laravel Socialite

Socialite is Laravel's official package for handling OAuth authentication.

Run this command to install it:

composer require laravel/socialite
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Google OAuth in Laravel

Add your Google credentials to the .env file:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://127.0.0.1:8000/auth/google/callback
Enter fullscreen mode Exit fullscreen mode

Then, add the Socialite configuration in config/services.php:

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

Step 4: Create Routes for Google Login

Add these routes in routes/web.php:

use App\Http\Controllers\GoogleController;

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

Step 5: Create Google Authentication Controller

Run the following command to generate the controller:

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

Then, update app/Http/Controllers/GoogleController.php:

namespace App\Http\Controllers;

use Exception;
use App\Models\User;
use Illuminate\Http\Request;
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 {
            $googleUser = Socialite::driver('google')->user();

            // Check if a user with this email exists
            $user = User::where('email', $googleUser->email)->first();

            if (!$user) {
                // Create a new user if not found
                $user = User::create([
                    'first_name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'google_id' => $googleUser->id,
                    'password' => bcrypt(uniqid()), // Random hashed password
                ]);
            }

            // Log in the user
            Auth::login($user);
            return redirect()->route('dashboard')->with('success', 'Login successful!');
        } catch (Exception $e) {
            return redirect()->route('login')->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Add Google Login Button to Your View

In your login page view (resources/views/auth/login.blade.php), add the Google login button:

<a href="{{ route('google.login') }}" class="btn btn-danger">Login with Google</a>
Enter fullscreen mode Exit fullscreen mode

Step 7: Test the Integration

  1. Start your Laravel development server:
   php artisan serve
Enter fullscreen mode Exit fullscreen mode
  1. Open http://127.0.0.1:8000/login and click "Login with Google."
  2. Sign in with your Google account.
  3. If everything is set up correctly, the user will be logged in and redirected to the dashboard.

Conclusion

You have successfully implemented Google login in your Laravel application using Socialite. This method enhances security and improves user experience by allowing authentication without requiring passwords.

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay