Laravel 10 Socialite Login with Google Example Tutorial
In this comprehensive guide, you are going to learn how to build a login with Goggle in Laravel using Laravel external libraries such as Socialite, Jetstream, and Livewire.
To build a login with a Google account in the Laravel system, we need to have a Gmail email account. This gmail account will help us to create an account with the Google developer console. In the developer console, we can grant access to create the Google client id and client secret.
You will be building a small yet dynamic Laravel Google Login system. Hence, we will use the Laravel Livewire library from the front-end design’s outlook.
This library allows the building of modern, reactive, dynamic interfaces using Laravel Blade templating language. This stack unleashes the power that you can use to integrate Google Login in the Laravel application.
How to Implement Goggle Login in Laravel 10 with Socialite
- Step 1: Create Laravel Project
- Step 2: Build Database Connection
- Step 3: Add Jetstream Package
- Step 4: Setting Up Socialite
- Step 5: Insert Google Property in Users Table
- Step 6: Get Google Client ID and Secret
- Step 7: Build New Controller
- Step 8: Create New Routes
- Step 9: Build Login with Google View
- Step 10: Run Development Server
Create Laravel Project
You have to start with building a new Laravel app. Ensure that you have installed composer in your system.
composer create-project laravel/laravel --prefer-dist laravel-google-login-example
Build Database Connection
After login, we will save the user record in the database hence opening the .env file and define the database credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=
If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.
UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
Add Jetstream Package
Let us run the command and install the JetStream module; it grants us access to use custom authentication templates built with Tailwind CSS.
composer require laravel/jetstream
php artisan jetstream:install livewire
Run the given command to install imperative npm packages:
npm install
npm run dev
Migrate the info to db through given command.
php artisan migrate
Setting Up Socialite
Laravel doesn’t come with a socialite library; therefore, we have to install the socialite package in our app.
composer require laravel/socialite
In order to install and set Socialite package, you have to add the given registry in the config/app.php file.
....
....
'providers' => [
....
....
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
....
....
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
....
....
Insert Google Property in Users Table
In the database, we now have to add the new property. This property will store the Google-authenticated users’ information.
php artisan make:migration google_social_auth_id
After executing the above command a new file will be created by the name of database/migration/google_social_auth_id.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function ($table) {
$table->string('gauth_id')->nullable();
$table->string('gauth_type')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function ($table) {
$table->dropColumn('gauth_id');
$table->dropColumn('gauth_type');
});
}
};
Quickly look for app/Models/User.php file and add the given code.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'gauth_id',
'gauth_type'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'profile_photo_url',
];
}
Assimilate the google auth property in the database.
php artisan migrate
Get Google Client ID and Secret
To create and get the Google client id and client secret, you must follow the given process:
1. You have to visit the official google dev site, hence jump on to Google Developers Console.
2. You have to click on Select a project, create a New Project, then press on Create button.
3. On the left side of the screen, click on the OAuth consent screen, then choose the External radio button and click on Create button.
4. Define your Application name, User Support email, App domain, Developer contact information, then click on the Save and Continue button.
5. Click on Credentials, then click on the CREATE CREDENTIALS button; after the dropdown opens, click on the OAuth client ID.
6. After the Create OAuth the client ID page opens; you must fill in the Application type and App Name.
7. You must add the site path in the Authorized JavaScript origins tab and then add the path in the Authorized redirect URIs. This url helps your users to redirect to the url after Google grants them access.
8. Now, the google OAuth client id and secret key created.
You have created the google account credentials; further, you have to define them in the laravel configuration file.
Go to the config/services.php file and add the google credentials array. Make sure to replace the client id and secret with your original google cloud dev credentials.
<?php
return [
'google' => [
'client_id' => 'xxxx',
'client_secret' => 'xxx',
'redirect' => 'http://127.0.0.1:8000/callback/google',
],
];
Build New Controller
It time to create a new controller; you can go ahead and run the given command.
php artisan make:controller GoogleController
Open the app/Http/Controllers/GoogleController.php file and place the suggested code.
<?php
namespace App\Http\Controllers;
use Auth;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
class GoogleController extends Controller
{
public function signInwithGoogle()
{
return Socialite::driver('google')->redirect();
}
public function callbackToGoogle()
{
try {
$user = Socialite::driver('google')->user();
$finduser = User::where('gauth_id', $user->id)->first();
if($finduser){
Auth::login($finduser);
return redirect('/dashboard');
}else{
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'gauth_id'=> $user->id,
'gauth_type'=> 'google',
'password' => encrypt('admin@123')
]);
Auth::login($newUser);
return redirect('/dashboard');
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
}
Create New Routes
Now you will create a request URL for signing-in with google in laravel. Routes are formed within the routes folder.
You can go ahead and create routes by adding the code to the routes/web.php file.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GoogleController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('auth/google', [GoogleController::class, 'signInwithGoogle']);
Route::get('callback/google', [GoogleController::class, 'callbackToGoogle']);
Build Login with Google View
To integrate login with google button; enter into the views/auth/login.blade.php file. You have to add the given code in this template.
<x-guest-layout>
<x-authentication-card>
<x-slot name="logo">
<x-authentication-card-logo />
</x-slot>
<x-validation-errors class="mb-4" />
@if (session('status'))
<div class="mb-4 font-medium text-sm text-green-600">
{{ session('status') }}
</div>
@endif
<form method="POST" action="{{ route('login') }}">
@csrf
<div>
<x-label for="email" value="{{ __('Email') }}" />
<x-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus autocomplete="username" />
</div>
<div class="mt-4">
<x-label for="password" value="{{ __('Password') }}" />
<x-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
</div>
<div class="block mt-4">
<label for="remember_me" class="flex items-center">
<x-checkbox id="remember_me" name="remember" />
<span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
</label>
</div>
<div class="flex items-center justify-end mt-4">
@if (Route::has('password.request'))
<a class="underline text-sm text-gray-600 hover:text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" href="{{ route('password.request') }}">
{{ __('Forgot your password?') }}
</a>
@endif
<x-button class="ml-4">
{{ __('Log in') }}
</x-button>
<a href="{{ url('auth/google') }}" style="margin-top: 0px !important;background: #C84130;color: #ffffff;padding: 8px;border-radius:6px;" class="ml-2">
<strong>Login with Google</strong>
</a>
</div>
</form>
</x-authentication-card>
</x-guest-layout>
Run Laravel Server
You have ultimately reached to the last step. Next and the last thing is to run the laravel app server.
php artisan serve
You can test the app with given url.
http://127.0.0.1:8000/login
Conclusion
Laravel is an all-time favorite application development framework. Because of its profound yet clear code structure with elegant syntax, it is still on top even in 2023.
Throughout this post, we tried to build a login with google in the laravel application using laravel socialite and other third-party libraries. We hope you will love this guide and mail us your feedback.