Tuesday, January 21, 2025
HomePHPGoogle social login integration utilizing Laravel Socialite

Google social login integration utilizing Laravel Socialite


by Vincy. Final modified on November twenty seventh, 2024.

The social login facilitates customers by simplifying the login effort with a single click on. It reduce shot the handbook signup and login course of saves time. Finish customers choose this technique and therefore your signup price will enhance.

Allow us to see learn how to combine the Google social login function in a Laravel utility. A bundle named Laravel Socialite helps social logins with Google, Fb, X, LinkedIn, GitHub and Slack through API.

This bundle connects the social login circulation with the Laravel auth cases. All we have to do is to import and name them from the login handlers.

Laravel Social Login Google

Steps setup Google social login in Laravel

I listed all of the steps to construct a social login even from constructing a Laravel mission. If you’re very acquainted with Laravel setup and you’ve got Google shopper keys, simply begin from level 4.

  1. Arrange a brand new Laravel mission.
  2. Set up Laravel Socialite bundle.
  3. Generate Google OAuth shopper keys.
  4. Configure Google OAuth keys and callback URL to Laravel.
  5. Construct social login routes, app mannequin and controller lessons.
  6. Add Google social login button to the template.

If you’re searching for the code to combine Google OAuth login utilizing core PHP, get it from the linked tutorial.

1. Arrange a brand new Laravel mission

Step one is to create the laravel-social-login mission through composer.

composer create-project laravel/laravel laravel-social-login

Create a database db_laravel_social_login and configure credentials within the Laravel app’s .env file.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_laravel_social_login
DB_USERNAME=root
DB_PASSWORD=

Go to the mission location through terminal cd laravel-social-login.  Then, do database migration through php artisan migrate command.

2. Set up Laravel Socialite bundle

Set up the Laravel Socialite bundle to the appliance.

composer require laravel/socialite

I put in Laravel auth to get the authentication views and the required dependancies.

composer require laravel/ui
php artisan ui vue --auth

Run the npm instructions to have the libraries for the login UI elements.

npm set up

Run construct if you’re utilizing the Vite software.

npm run construct

Or else if you’re utilizing Laravel Combine, then run dev.

npm run dev

With the reference of the Laravel Auth:: cases, the login state dealing with and redirects are taking place.

3. Generate Google OAuth shopper keys

These are the steps to get the Google OAuth keys. Chances are you’ll be acquainted with the beneath steps if in case you have already labored with Google providers.

  • Login to Google cloud console.
  • Create new mission or select current one.
  • Select API and Providers.
  • Configure the OAuth consent display.
  • Select Credentials->CREATE CREDENTIALS->OAuth shopper ID.
  • Give the next internet shopper particulars:
    • Utility kind: Internet Utility
    • Approved JavaScript origin: <your area>
    • Approved redirect URIs: <Callback URL>
  • Copy the Consumer ID and the Secret key.

Google Cloud Brand

Create a brand new Google console mission and configure the OAuth consent display

google login oauth consent screen

Create OAuth credentials

create google oauth client credentials

google client project setting

Copy the shopper ID and secret key

Google OAuth Client ID Secret

The above steps are required for any utility integrating Google cloud providers. On this weblog additionally we’ve seen examples for integrating Google providers in a PHP utility. I linked 2 of them beneath.

  1. Sending electronic mail with Gmail XOAUTH2
  2. Writing to Google Sheets API.

4. Configure Google OAuth keys and callback URL to Laravel

There are three configuration as listed beneath.

  1. Google shopper ID
  2. Google secret key
  3. Callback URL

Create environmental constants for the shopper id and secret key within the .env

GOOGLE_CLIENT_ID = paste shopper id right here
GOOGLE_CLIENT_SECRET = paste secret key right here

Now, it’s able to configure the social login keys and URLs to the appliance config file. Open providers.php file within the Laravel utility root.

the beneath code exhibits the tactic of configuring Google social login constants with the Laravel.

In the identical manner the Github, Fb and different social login configurations will be enabled on this file. I’ll submit all of the integrations within the upcoming tutorials.

config/providers.php

'google' => [
   'client_id' => env('GOOGLE_CLIENT_ID'),
   'client_secret' => env('GOOGLE_CLIENT_SECRET'),
   'redirect' => 'http://127.0.0.1:8000/google/login/callback',
],

5. Construct social login routes, app mannequin and controller lessons

This part specifies the adjustments required on the Laravel routes, fashions and controllers.

Internet routes

Add the next two URL guidelines to the Laravel internet routes. One is for redirecting to the Google OAuth endpoint for sending the authorization request. Then, the opposite is to name again the Laravel utility.

routes/internet.php

<?php
Route::get('/google/login/redirect', [GoogleOAuthController::class, 'google_login_redirect'])->title('google_login_redirect');
Route::get('/google/login/callback', [GoogleOAuthController::class, 'google_login_callback']);
?>

Consumer mannequin

The consumer mannequin will comprise the fields provide you with the default Laravel authentication system.

Add the supplier and the provider_id fields to the Consumer mannequin’s fillable array. Open Consumer mannequin and let the $fillable as proven beneath.

These two columns are to avoid wasting the social login supplier like Google, Fb and its distinctive id belongs to the consumer logged-in.

<?php
namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

class Consumer extends Authenticatable
{
    ...
    protected $fillable = [
        'name',
        'email',
        'password',
        'provider',
        'provider_id',
    ];

    ...
}
?>

Create GoogleOAuthController controller

Make the GoogleOAuthController class utilizing php artisan make:controller GoogleOAuthController
The controller has two features as listed beneath.

  1. google_login_redirect: It sends the OAuth request to Google.
  2. google_login_callback: It captures API response in a callback.

Within the google_login_callback(), it receives the Google consumer particulars and saves to the database.

The Consumer::updateOrCreate() perform is used to place the consumer entry with respect to the distinctive provider_id. This perform returns the authenticatable consumer object. With this object the Auth::login() turns the consumer logged in.

app/Http/Controllers/GoogleOAuthController.php.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesAuth;
use LaravelSocialiteFacadesSocialite;

class GoogleOAuthController extends Controller
{
    public perform google_login_redirect() {
        return Socialite::driver('google')->redirect();
    }

    public perform google_login_callback() {
        $googleUser = Socialite::driver('google')->consumer();

        $consumer = Consumer::updateOrCreate([
            'provider_id' => $googleUser->id,
        ], [
            'name' => $googleUser->name,
            'email' => $googleUser->email,
            'provider' => 'google',
            'provider_id' => $googleUser->id
        ]);
     
        Auth::login($consumer);
     
        return redirect('/house');
    }
}
?>

6. Add Google social login button to the template

By putting in Laravel/ui, it brings the auth templates in to the appliance. The login.blade.php is the view file that incorporates the default Laravel login kind.

Beneath code give the Google login button with acceptable hyperlink to redirect. Copy this code and put it into the login template.

sources/views/login.blade.php

<div class="row mb-0">
    <div class="col-md-8 offset-md-4">
        <a href="https://phppot.com/laravel/laravel-social-login-via-google/{{ route("google_login_redirect') }}">
            <button kind="button" class="btn btn-primary px-4 py-2">
                <img src="photographs/google-logo.png" width="24" class="mx-1" /> Sign up through Google
            </button>
        </a>
    </div>
</div>

Output

By clicking the “Sign up with Google” button, it’ll ask to “Proceed” entry profile through internet shopper.
Allow App to Access Profile

After processing social login request, Google redirects to the callback URL. This callback endpoint turns the logged-in state on and redirects to the dashboard.
Laravel Auth Dashboard Template
Obtain

Vincy
Written by Vincy, an internet developer with 15+ years of expertise and a Masters diploma in Pc Science. She focuses on constructing trendy, light-weight web sites utilizing PHP, JavaScript, React, and associated applied sciences. Phppot helps you in mastering internet growth by means of over a decade of publishing high quality tutorials.

↑ Again to Prime

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments