Loading image

Blogs / Programming

How to Seamlessly Integrate Google Login in Laravel (A Step-by-Step Guide)

How to Seamlessly Integrate Google Login in Laravel (A Step-by-Step Guide)

  • showkat ali
  • 3 min read
  • 0 Comments
  • 127 View

Quick Guide: Add Google Login to Laravel

 

This guide provides the minimal steps to get Google login working in a Laravel project using Socialite.

 

Step 1: Get Google API Credentials

 

  1. Go to the Google Cloud Console.

  2. Create a new project.

  3. Go to APIs & Services > OAuth consent screen.

    • Choose External and fill in the required app name, support email, and developer contact.

  4. Go to APIs & Services > Credentials.

    • Click + Create Credentials > OAuth client ID.

    • Set Application type to Web application.

    • Under Authorized redirect URIs, add your callback URL. For local testing:

      http://127.0.0.1:8000/auth/google/callback
      
  5. Click Create. Copy the Client ID and Client Secret.


 

Step 2: Install and Configure Laravel Socialite

 

  1. Install the package:

    composer require laravel/socialite

     

  2. Add credentials to .env
    GOOGLE_CLIENT_ID=YOUR_CLIENT_ID
    GOOGLE_CLIENT_SECRET=YOUR_CLIENT_SECRET
    GOOGLE_CALLBACK_URL=http://127.0.0.1:8000/auth/google/callback
  3. Add config to config/services.php
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_CALLBACK_URL'),
    ],

Step 3: Update User Database

 

  1. Create a migration:

    php artisan make:migration add_google_id_to_users_table --table=users

     

  2. Edit the new migration file (in database/migrations/):
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('google_id')->nullable()->unique()->after('id');
            $table->string('password')->nullable()->change(); // Make password nullable
        });
    }
    
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('google_id');
            $table->string('password')->nullable(false)->change();
        });
    }
  3. Run the migration:
    php artisan migrate
  4. Update User Model (in app/Models/User.php):
    protected $fillable = [
        'name',
        'email',
        'password',
        'google_id', // Add this
    ];

Step 4: Define Routes

 

In addition, add two routes for the login process:

use App\Http\Controllers\GoogleLoginController;

Route::get('/auth/google/redirect', [GoogleLoginController::class, 'redirectToGoogle'])->name('google.redirect');
Route::get('/auth/google/callback', [GoogleLoginController::class, 'handleGoogleCallback'])->name('google.callback');

Step 5: Create the Controller

 

  1. Create the controller:

  2. php artisan make:controller GoogleLoginController
  3. Add the logic (to app/Http/Controllers/GoogleLoginController.php):
  4. <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Laravel\Socialite\Facades\Socialite;
    use App\Models\User;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Hash;
    use Illuminate\Support\Str;
    
    class GoogleLoginController extends Controller
    {
        // Redirect user to Google
        public function redirectToGoogle()
        {
            return Socialite::driver('google')->redirect();
        }
    
        // Handle the callback from Google
        public function handleGoogleCallback()
        {
            try {
                $googleUser = Socialite::driver('google')->user();
    
                // Find or create user
                $user = User::updateOrCreate(
                    ['google_id' => $googleUser->id],
                    [
                        'name' => $googleUser->name,
                        'email' => $googleUser->email,
                        'password' => Hash::make(Str::random(24)) // Set a random password
                    ]
                );
    
                // Log the user in
                Auth::login($user);
    
                return redirect('/dashboard'); // Redirect to your desired page
    
            } catch (\Exception $e) {
                // Handle error
                return redirect('/login')->with('error', 'Login with Google failed!');
            }
        }
    }

 

Step 6: Add the Login Button

 

In your login.blade.php file (or any other view), add the link:

<a href="{{ route('google.redirect') }}">
    Login with Google
</a>

 

Conclusion:


Adding Google login to your Laravel app is a fast and powerful way to improve user experience. By using the Socialite package, you replace complex registration forms with a secure, one-click login, which can increase sign-ups and make your users happier.

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance.

0 Comments

Post Comment