Hello coders! In this article we learn, how to integrate Laravel login with Google.
Firstly, we will learn how to create an app credentials at google. Secondly we will code for implement it with Laravel authentication.
Most importantly, we have to stick with the same code and process atleast for this demo to run successfully, after that you can modify it as per need.
Setup and implement Google App (Auth Client) for google login.
First go to google developer account console.
https://console.developers.google.com/
You will see bellow page [after login] where i am trying this in August 2020 so it might differ in future.
If you don’t created any project yet then please create a project for our demo or your web application. Click on “Create Project“.
You will be land on below page after that.
Here we find two option two enter. first is “Project Name” and second is “Project ID“.
Therefore please add project name relevant to website application and keep “Project ID” as it is which auto fill by google. Click on “Create” button.
We will usually land on above screen once project is created. Now we need to generate Credentials with “OAuth client ID” to access API further.
As a result you will see below screen where we need to choose “OAuth Client ID” from the options to create credentials.
Next, If we have not added “Consent” then we need to add first by following below screen. if you have already added it then skip to next step.
As soon as we will click on the button it will open below page with two options.
We have to choose the “External” as it describes and as I don’t have Gsuite subscription.
Proceed with further step by clicking “Create” button. and you will be asked for few detail about consent with application detail as below.
For now please just add “Application name” for demo purpose or fill relevant information and proceed.
After submitting the information we will prompted on below success page that confirms out consent is ready.
Now the OAuth consent is ready, its time to create “OAuth Client ID“.
We have to choose “Web application” from the given options. and you will be redirect to next page below.
Please fill required fields from the given form related to our web app. and for demo please keep the URL and redirect URL same as mentioned in screenshot.
Once we will done with “Oauth Client ID” we will be prompted to credentials with credentials “Client ID” and “Client Secret“.
Please copy those credentials somewhere safe in local PC or wherever you think is safe.
Okay so we are done here from Google part of it. now time to setup Laravel application with google credentials.
Install Laravel
Click here to read step by step guide to know how to install Laravel
$ composer create-project --prefer-dist laravel/laravel laravel-login-with-google "5.8.*"
Make sure that your storage folder have write permission here.
Its time to create the database and update “.env” accordingly
Now make authentication configuration and migrate stuff.
$ php artisan make:auth
$ php artisan migrate
Install Socialite package
Now we have to configure setup for our Socialite package.
We do this by updating to “app.php” inside ”config” folder and insert the below codes.
In “app.php”, scroll down to “providers” section and add Socialite service provider package as below:
Laravel\Socialite\SocialiteServiceProvider::class,
Inside the file “app.php” we will set “aliases” by adding below configuration line.
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
Updated “config” > “service.php” to configure socialite services by adding below code.
'google' => [
'client_id' => env('GOOGLE_APP_KEY'),
'client_secret' => env('GOOGLE_APP_SECRET'),
'redirect' => env('GOOGLE_REDIRECT'),
],
Time to set all above ENV variables to .env file.
GOOGLE_APP_KEY=XXXXXXXXXXXXXXXXXXXXX
GOOGLE_APP_SECRET=XXXXXXXXXXXXXXXXXXXXX
GOOGLE_REDIRECT=http://127.0.0.1:8000/callback-google
Just for this example, we will set the “GOOGLE_REDIRECT” variable same as mentioned.
Controller creation and code implementation.
Execute below command to create new controller to handle operation and process.
$ php artisan make:controller SocialAuthGoogleController
We need to create functions inside controller: redirect() function to redirect the user to google page for authentication, and callback() function is used to handle user authentication.
Inside SocialAuthGoogleController please add below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Socialite;
use App\Services\SocialGoogleAccountService;
class SocialAuthGoogleController extends Controller
{
/**
* Create a redirect method to google api.
*
* @return void
*/
public function redirect()
{
return Socialite::driver('google')->redirect();
}
/**
* Return a callback method from google api.
*
* @return callback URL from google
*/
public function callback(SocialGoogleAccountService $service, Request $request)
{
$user = $service->createOrGetUser(Socialite::driver('google')->user());
// dd($user);
auth()->login($user);
return redirect()->to('/');
}
}
Time to add routes based on controller and function inside.
//For Google login
Route::get('/redirect', 'SocialAuthGoogleController@redirect');
Route::get('/callback-google', 'SocialAuthGoogleController@callback');
Step to navigate to ‘resources’ > ‘views’ > ‘auth’ > ‘login.blade.php’.
Therefore, we will add the Google Login button. I have used one of live URL of google login button image. You can use your own.
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
@if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif
</div>
</div>
</form>
<div class="row">
<div class="col-12 text-center">
<p>OR</p>
</div>
<div class="col-12 text-center">
<div class="form-group">
<div class="col-md-12 col-md-offset-4">
<a href="{{ url('/redirect') }}" >
<img src="https://www.ainotes.org/images/google-button.svg" alt="Login with google" height="40" />
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
Create model and code implement.
Path: app > SocialGoogleAccount.php
<?php
// SocialGoogleAccount.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SocialGoogleAccount extends Model
{
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Create database migration with below code
$ php artisan make:migration create_social_google_accounts_table
Moreover navigate to “database” > “migrations” > “create_social_google_accounts_table.php” and add lines of code as mentioned below.
<?php
// create_social_google_accounts.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSocialGoogleAccountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('social_google_accounts', function (Blueprint $table) {
$table->integer('user_id');
$table->string('provider_user_id');
$table->string('provider');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('social_google_accounts');
}
}
Time to Run below command in another words we are done with migration part.
$ php artisan migrate:refresh
Create Service for the Google login
Path: app > Services > SocialGoogleAccountService.php
<?php
namespace App\Services;
use App\SocialGoogleAccount;
use App\User;
use Laravel\Socialite\Contracts\User as ProviderUser;
use Illuminate\Support\Facades\Mail;
class SocialGoogleAccountService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialGoogleAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialGoogleAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'password' => md5(uniqid()), // we use md5 where user will not able to use this as normal login :)
'role'=>'customer',
]);
if($user){
$data = [];
$data['email'] = $providerUser->getEmail();
$data['name'] = $providerUser->getName();
}
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
Therefore, We have successfully integrated google login to our laravel application.
Lastly, final step to run below command to run Laravel
$ php artisan serve
As a result we will see below screen as an output.
When we click on “Signin with Google” button, it will open page as below.
Once we authenticate success it will redirect to our laravel app with login auth.
However you can also find below Github Repo for quick installation.
In conclusion, following up explanation with steps are easy. Feel free to comment and ask questions if anything.
Awesome!! It’s done. Please share your thoughts with suggestions in comment if any.
PS. Checkout another tutorial about Twitter login integration with Laravel