Tuesday, March 17, 2020

Laravel 6/7 - Login with Google Socialite

Laravel 6/7 - Login with Google Socialite


Here I explain step by step the Laravel 6/7 - login with google socialite. laravel 7/6 socialite offers API to log in with a Gmail account. We can simply log in to the Laravel project using the Google account.

As we know, social media are becoming increasingly popular in the world. Everyone has a social account like Gmail, Facebook etc. I think most of them also have a Gmail account. So if you have a social login in your app, it will be awesome. You have connected more people to your website because most people do not want to fill out the registration or registration form. If there is a social media login, it will be amazing.

So if you also want to implement the login with a Gmail account, I will help you step by step Laravel 6/7 - login with google socialite. Let's follow the tutorial and implement it.


Step 1: Install Laravel 6


If you did not configure the Laravel 6 app in this step, we need a new Laravel 6 app. So run the following command and get a clean and fresh Laravel 6 app.

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


Step 2: Install Socialite


In the first step, we install the Socialite package, which provides an API for connecting to the Google account. So first open your terminal and run the following command:

composer require laravel/socialite

After installing the package above, we need to add providers and aliases to the configuration file, now open the config / app.php file and add the service provider and aliases.

'providers' => [

....

Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [

....

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

],


Step 3: Create Google App


In this step, we need the identification and secret of the Google client in order to receive information from other users. If you don't have a Google App account, you can create the following here: Google Developers Console.

Now you need to click on credentials and select the first option oAuth and click on the button Create new customer ID. Now you can see the next slide:

After creating an account, you can copy the customer ID and secret.

Now you need to configure the app ID, secret and callback URL in the configuration file. So open config / services.php and set the ID and secret as follows:

config/services.php
return [

    ....

    'google' => [

        'client_id' => 'app id',

        'client_secret' => 'add secret',

        'redirect' => 'http://localhost:8000/auth/google/callback',

    ],

]


Step 4: Create Authentication


In this step we need to install the Laravel user interface and generate authentication in the Laravel 6 application. Therefore, run the following command:

Install Laravel UI:

composer require laravel/ui

Create Auth:

php artisan ui bootstrap --auth

NPM Install:

npm install

Run NPM:

npm run dev


Step 5: Add Database Column


In this step, we first need to create a migration to include google_id in your user table. So let's run the following command:

php artisan make:migration add_google_id_column

Migration
<?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()

    {

        //

    }

}

Update mode as follows:

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 6: Create Routes


After adding the google_id column first, you'll need to add a new path to sign in to Google. So let's add the following route to the route.php file.

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 7: Create Controller


After adding the path, we need to add the Google authentication method. This method processes the Google callback URL, etc. First, paste the following code into your GoogleController.php file.

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 8: Update Blade File


Ok, now we have to finally add the sheet view, so first create a new file login.blade.php and enter the following code:

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 - ItSolutionStuuf.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


Ok, now you can get started, open your browser and check here: URL + '/ login'.

I hope this tutorial Laravel 6/7 - login with google socialite could help you .

Thanks…



















0 comments:

Post a Comment

Please don't enter any spam link in the comment box.