Skip to content

Webtuts

Online Web Tutorial

  • Laravel
  • Laravel 8
  • jQuery
  • CodeIgniter
  • CodeIgniter 4

Laravel 7 Socialite Login with Google Account Example

February 14, 2021 web-tuts Laravel

In this example i explain Laravel 7 Socialite Login with Google Account Example. Also  laravel 7 socialite provide api to login with gmail account. We can easily login using google account in laravel project.

Larave 7 Login with google account is a become more and more popular in the world. Every account is link by google account and facebook account.

Laravel 7 Socialite Login with Google Account Example

Step 1: Install Laravel 7

In this step i install fresh laravel 7 application and setup laravel 7 application. So run the following command to get laravel 7 application.

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

Step 2: Install Laravel Socialite

In this step i install laravel socialite package that provide api to connect with google account. So run the following command on your terminal ang get laravel socialite package.

composer require laravel/socialite

After install the laravel socialite package we add providers and aliases in config file, So open your config/app.php file and add the following service provider and aliase.

'providers' => [

    ....

    Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [

    ....

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

],

Step 3: Create Google App

In this step we require google client id and secret that way we can get other user information. so first you create google app account then you can create from here : Google Developers Console.

After create account you can copy your client id and secret.

Read Also :  How to Flash Message in Laravel Example

Now you have to set your app id, secret and call back url in config file so open the first config/services.php and set id and secret following code:

config/services.php

return [
    ....
    'google' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://localhost:8000/auth/google/callback',
    ],
]

Step 4: Create Auth

In this step we install laravel ui and generate auth in laravel 7 application so, let’s run following command in your terminal:

Install Laravel UI (User Interface)

composer require laravel/ui

Create Auth:

php artisan ui bootstrap --auth

NPM Install:

npm install

Run NPM:

npm run dev

Step 4: Add Database Column

In this step i create migration for add google_id in your user table. So first run bellow command:

php artisan make:migration add_google_id_column

Migration : add_google_id_column

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddGoogleIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('google_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Add google_id clomun in your mode like this way:

app/User.php

<?php
  
namespace App;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
   
class User extends Authenticatable
{
    use Notifiable;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'google_id'
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
   
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Step 5: Create Routes

In this step we create route for login with google.

Read Also :  Laravel 8 Database Seeder Example

app/Http/routes.php

Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();
  
Route::get('/home', 'HomeController@index')->name('home');
Route::get('auth/google', 'Auth\GoogleController@redirectToGoogle');
Route::get('auth/google/callback', 'Auth\GoogleController@handleGoogleCallback');

Step 6: Create Controller

In this step we create controller and add method of google auth that method will handle google callback url and etc.

app/Http/Controllers/Auth/GoogleController.php

<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\User;
  
class GoogleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }
      
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGoogleCallback()
    {
        try {
    
            $user = Socialite::driver('google')->user();
     
            $finduser = User::where('google_id', $user->id)->first();
     
            if($finduser){
     
                Auth::login($finduser);
    
                return redirect('/home');
     
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
    
                Auth::login($newUser);
     
                return redirect('/home');
            }
    
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Step 7: Update Blade File

resources/views/auth/login.blade.php

@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">Laravel 6 - Login with Google Account Example - Web-tuts.com</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
                                  
                                <a href="{{ url('auth/google') }}" style="margin-top: 20px;" class="btn btn-lg btn-success btn-block">
                                  <strong>Login With Google</strong>
                                </a> 
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

I hope you understand login with google accpunt…

Step 1: Install Laravel 6

Read Also :  Laravel Resize Image Before Upload

Related posts:

  • How to Flash Message in Laravel Example
  • jQuery Get Image Src and Set Image Src
  • Laravel 7 Login with Linkedin using Socialite
  • Laravel 7 Login with Github Example
  • Laravel Where Not in Eloquent Example
  • Laravel Firebase Push Notification Example
  • How to Integrate Login with Facebook in Laravel
  • Laravel Livewire Dependant Dropdown Example
  • How to Generate Dynamic PDF from HTML in Laravel
  • Laravel 8 Crud Operations Example
GmailGoogle APIGoogle AuthLaravelLaravel 6Laravel 7Login with GoogleSocialite

Post navigation

Previous Post:Laravel Insert Data using Create Method
Next Post:Laravel 7 Login with Linkedin using Socialite

Recent Posts

  • How To Seed Data In Laravel 9
  • Marge Multiple PDF In Laravel 9
  • Laravel 9 CRUD Operation Tutorial For Beginner
  • Laravel 9 Generate PDF File using DomPDF
  • Laravel 9 Mail | Laravel 9 Send Email Example
  • Laravel 9 Create Zip File And Download
  • Laravel 9 Socialite Login with Google Example
  • Laravel 9 Image Upload Example
  • How to Get Client IP Address in Laravel 9?
  • Laravel 8 Print Last Query Example
  • Laravel Select with Sum Query Example
  • Laravel 8 Auth Login with Username or Email
  • Laravel 8 Find Nearest Location By Latitude and Longitude
  • 404 Not Found but Route Exist in Laravel
  • Laravel 8 Clear Cache of Route, View & Config
  • Laravel 8 Change Password with Current Password Validation
  • Laravel Carbon Get First Day of Specific Month Example
  • Laravel 8 Database Seeder Example
  • Laravel Eloquent doesntHave() Condition Example
  • Restore Back Deleted Records in Laravel 8
  • Laravel 8 Multiple Database Connections
  • Laravel 8 Download File Example
  • PHP Array Push Key Value Example
  • How To Add Days To Current Date In Laravel Blade
  • Moment JS Get Last Date of Month Example
  • Laravel Carbon Convert String to Date Example
  • Moment Get Current Week Number Example
  • Laravel Carbon Get Year from Date Example
  • JavaScript Array Remove Element
  • Laravel Carbon Get Last Day of Month Example
  • How To Validate Upload File Type Using JavaScript
  • How to Create Multilingual Website in Laravel 8
  • Laravel 8 Automatic Database Encryption Decryption
  • How To File Upload In CodeIgniter 4 Example
  • How to Get Month Name from Date in Laravel 8
  • CRUD with Image Upload in Laravel 8 Example
  • CodeIgniter 4 Watermark Image Example
  • jQuery Get All Checked Checkbox Values in Array
  • CodeIgniter 4 Google Bar & Line Charts Example
  • Codeigniter 4 Ajax Image Upload With Preview Example
  • Space Not Allowed Validation in Laravel Example
  • Laravel 8 View Render Example
  • Laravel 8 Form Validation Example
  • Laravel 8 Signature Pad Example
  • Laravel 8 cURL HTTP Request Example
  • Laravel 8 Datatables Filter with Dropdown
  • Laravel 8 Pagination Example
  • Laravel 8 QR Code Generate Example
  • Laravel 8 Highcharts Example
  • Laravel 8 Multi Step Form Example
© Copyright 2020 Web-tuts.com. All rights reserved. Home Privacy Policy Contact Us Terms of Use