Laravel Socialite Login with Gmail Account

Laravel Socialite Login with Gmail Account

In this tutorial, I will explain the step-by-step login with your Google account in Laravel 8/7/6 using the Socialite package. The socialite package provided a login API for Laravel to log in with a Gmail account. Users can easily use their google account and log in to your project.


In today's world, social media has more and more popular around the world. Most people have their own social accounts like Facebook, Twitter, Gmail, etc. Most probably, the Gmail account is the most used and popular. If you have added Google login in your application, then that would be awesome. Most people can easily connect with your website and can enjoy the application.

 

Follow the tutorials and implement your google login today.


Preview:




 

Step by step guide to Login with Google in Laravel.


Step 1: Install Laravel

In this step, you need to check whether you have installed Laravel in your system. If not, you can install using the following command:


composer create-project --prefer-dist laravel/laravel googleLogin


This command installs the latest copy of Laravel in your system.


Step 2: Install Socialite

In this step, you need to install the Socialite package in your project. Run the following command to download the package:


composer require laravel/socialite


After installing the package, you need to add providers and aliases to the config file. Now open the config/app.php file.



Now, you see the app.php file.





After opening the file, add the following lines of code in the providers and aliases array respectively:

 

'providers' => [

 

        Laravel\Socialite\SocialiteServiceProvider::class,

 

 ],


'aliases' => [

 

        'Socialite' => Laravel\Socialite\Facades\Socialite::class,

 

 ],

After adding the above lines of code your code will look like this:





Step 3: Create Google App account

In this step, we need a client id and secret id. You can get the google app account from here - Google Developers ConsoleYou can find it below in the screenshot.



Now, click on the Credentials on the side navigation menu and choose the second option oAuth and click Create new Client ID button. 








Here, you have to mention the redirect URL as shown in the above screenshot.

 

Step 4: Set client id, client secret, and callback

Here, you have to set client id, secret, and callback in the config file. Open the config/services.php file and set id, secret, and callback URL according to the following screenshot:



Keep in mind that, the redirect URL provided above should be the same as the redirect URL you have provided to your project on your google console account.


Step 5: Create Auth

In this step, you need to install Laravel UI and generate auth files in Laravel, so run the following command:

composer require laravel/ui

 

Create Auth:

php artisan ui bootstrap --auth

 

NPM Install:

npm install

 

Run NPM:

npm run dev

 

Step 6: Add Database Column

In this step, you need to add an additional column google_id in the users table migration file, model file, and database.


Migration





Model



Step 7: Create Routes

After adding google_id in the migration and model file we have to give a route for google login. Add following code in routes.php file.


Route::get('/', 'Frontend\HomeController@index')->name('home');

Route::get('auth/google', 'Auth\Google\LoginController@redirectToGoogle')
->name('google-login-proceed');

Route::get('auth/google/callback', 'Auth\Google\LoginController@handleGoogleCallback');


Step 8: Create Controller

After adding the route, we need to create Google Login Controller for handling the callback, URL, etc. Create a Login Controller inside the Auth folder with the following command:

 

php artisan make:controller Auth/Google/LoginController

 

app/Http/Controllers/Auth/LoginController.php


namespace App\Http\Controllers\Auth\Google;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Laravel\Socialite\Facades\Socialite;

use Illuminate\Support\Facades\Auth;

use Exception;

use App\User;

use Illuminate\Support\Str;

use Illuminate\Support\Facades\Hash;

class LoginController extends Controller

{

use AuthenticatesUsers;

public function __construct()
{
$this->middleware('guest')->except('logout');
}

public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();

// return Socialite::driver('google')->stateless()->redirect();
}

public function handleGoogleCallback()
{

try {

$user = Socialite::driver('google')->user();

// dd($user->getId());

$oauth_id = $user->getId();
// $user = Socialite::driver('google')->stateless()->user();

$finduser = User::where('google_id', $oauth_id)->first();

// dd($finduser);

if ($finduser) {

Auth::login($finduser);

return redirect('/');
} else {

$newUser = User::create([

'name' => $user->name,

'email' => $user->email,

'random_id' => Str::random(10),

'google_id' => $oauth_id,

'password' => Hash::make($user->name . '@123456')

]);

Auth::login($newUser);

return redirect('/');
}
} catch (Exception $e) {

return $e->getMessage();
}
}
}


Step 9: Update Blade File

At last, we need to add the URL to our login page for the google login feature to work. Add the following code to the login.blade.php file.

@extends('Frontend.layouts.master')
@section('content')
<div class="nav-info">
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<h3>Art Kith3>
<nav class="breadcrumbs">
<a href="">homea>
<span class="divider">/span>
Login
nav>
div>

div>
div>
div>

<section class="login-body">
<div class="container">
<div class="login">
<i class="fa fa-sign-in" aria-hidden="true">i>
<strong>Welcome!strong>
<span>Sign in to your accountspan>
@if ($errors->any())
<div class="alert alert-danger col-md-12">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}li>
@endforeach
ul>
div>
@endif

@if ($message = Session::get('error'))
<div class="alert alert-danger">
<p>{{ $message }}p>
div>
@endif


<form method="POST" class="login-form mt-3" action="{{ route('login') }}"
aria-label="{{ __('Login') }}">
@csrf

<fieldset>
<div class="form">
<div class="form-row">
<i class="fa fa-user" aria-hidden="true">i>
<label class="form-label" for="input">Emaillabel>
<input id="email" type="email" class="form-text

@error('email') is-invalid @enderror"
name="email" value="{{ old('email') }}"
required autocomplete="off" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}strong>
span>
@enderror
div>
<div class="form-row">
<i class="fa fa-eye" aria-hidden="true">i>
<label class="form-label" for="input">Passwordlabel>
<input id="password" type="password"
class="form-text @error('password') is-invalid

@enderror" name="password" required
autocomplete="off">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}strong>
span>
@enderror
div>
<div class="form-row bottom">
<div class="form-check">
<input type="checkbox" onclick="showPassword()">
<label for="show"> Show Passwordlabel>
div>
@if (Route::has('password.request'))
@isset($url)
<a
href="{{ route($url . '.' . 'password.request') }}" class="forgot">Forgot
Password?a>
@else
<a href="{{ route('password.request') }}"
class="forgot">Forgot Password?a>
@endisset
@endif
div>
<div class="form-row button-login">
<button class="btn btn-login form-control">Login
button>
div>

<p class="text-left mt-1 mb-2">Or, Login Withp>
<button type="button" class="btn btn-login form-control fb-btn">
<i class="fa fa-facebook pr-4" aria-hidden="true">i>
Facebook

button><br>
<a href="{{ route('google-login-proceed') }}">
<button type="button" class="btn btn-login form-control
google-btn">
<i class="fa fa-google-plus pr-4" aria-hidden="true">i>
Google
button>
a>
div>
<p class="text-left mt-1 mb-2">Are you a New Member ?p>
fieldset>
form>

div>
div>
section>
@endsection



Now, you are able to log in using your google account from your project.

Recent comments(0)

Please, Sign In to leave a reply