Today I came up with an interesting article. You want to get the way to do this? OK..First I will tell you about today's tutorial. This is a SIGN UP process using Gmail accounts. Most people say we have to host our web application in a host, to do this.. In Laravel, it's not needed guys! I tried this in my local machine.. Let's start!!!

Here we mainly use Laravel Socialite package.

Step 1 - Create new laravel project

composer create-project laravel/laravel GoogleLogin

Step 2 - Migrate database

Open the project folder and edit database configuration files.

.env file

config/database.php file


Before database migration, do this change to avoid migration errors... In your project folder, open Http/Providers/AppServiceProvider.php file and replace its code with this.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Open the database folder and go into migrations folder. Then open users migration file in your text editor. Edit the file like this.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Now open a cmd and type this command to migrate database. 

php artisan migrate

You will have the database tables now..


Now go to phpmyadmin and do some change. We have to add a default value for password field. Because it is not taken from the Google sign up. So give any password hash of a string you use as a testing password. Then the given value will be stored as the password for all users. Later you can create a way to change this password after logged in.
Example : 
For 111111 => Hash $2y$10$3GhzenR01ROU/5xeSppb8O570wo9.X0kvgglujG1f0rvyHmi7xzgO


Step 3 - Create the Laravel in-built Login System 

We have to create a login system to log in users. Laravel provides an easy way to do this! Open cmd and type this.

php artisan make:auth

Now we have the login system. This command will auto generate the routes, views, controllers automatically that is needed for login and registration.
Go and see the routes/web.php file..

Step 4 - Create a view for default main view

We need a main view to be displayed when we run the project. Let's create it!
resources/views/welcome.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    </head>
    <style type="text/css">
        body {
            font-family: 'Lato', sans-serif;
        }
    </style>
    <body>
    <div class="container" style="margin-top: 50px;">
        <div class="row">
            <div class="col-lg-3"></div>
            <div class="col-lg-6">
                <div class="jumbotron">
                    <h3 class="text-center">Google Sign in with Laravel</h3><br>
                    <a href="/login" style="margin: auto; display: block; font-size: 20px;" class="btn btn-link">Click here to Login</a>
                </div>
            </div>
            <div class="col-lg-3"></div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    </body>
</html>

This is the output : 

Step 5 - Include Laravel Socialite package into our project

We need the help of this package to create a Social login. So, open a cmd and type this command to include it.

composer require laravel/socialite

Important - Here I use Laravel 5.6.. If you are going to use version 5.3 or  below, you have to do another steps.. Visit the below link for it.
https://github.com/laravel/socialite/tree/2.0

Step 6 - Create a Google Console project

This is the most important part of the article. We have to use Google API to connect Google login with our project. So, we need to create a new project in Google Developer Console. Sign into a gmail account and type https://console.developers.google.com in your web browser.
I have created a short video to demonstrate the way to do it. Watch this video now..


Step 7 - Make arrangements in configuration files

.env file

GOOGLE_SERVER_KEY=AIzaSyC_g8Uj5GGAqnPZaZAmlVMkUj0DXOVw0Z8
GOOGLE_CLIENT_ID=1005365429600-iad31rfo94vk3h91efri17eei33a2v05.apps.googleusercontent.com
GOOGLE_APP_SECRET=9ZE8eJij5cGRnYbtxPdVBV8W
GOOGLE_REDIRECT=http://localhost:8000/login/google/callback
Important :
Here you have to include your project ID and secret key for GOOGLE_CLIENT_ID and GOOGLE_APP_SECRET. They are unique for a project credentials. Do not include my credentials. It will not work. Get them from your console dashboard. 

config/services.php file

Open this file and add this code section to the end of the file within the returning array! Use the previously included project ID and secret key for this also.

    'google' => [
        'client_id' => '1005365429600-iad31rfo94vk3h91efri17eei33a2v05.apps.googleusercontent.com',
        'client_secret' => '9ZE8eJij5cGRnYbtxPdVBV8W',
        'redirect' => 'http://localhost:8000/login/google/callback',
    ],

Step 8 - Replace Login Controller code

Now, we have to modify our Login controller. Need to add the Google Login functionality. For this replace the code in Login controller with this code.

<?php

namespace App\Http\Controllers\Auth;
use App\User;
use Socialite;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */

    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToGoogleProvider()
    {
        return Socialite::driver('google')->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleGoogleProviderCallback()
    {
        try{
            $user = Socialite::driver('google')->user();
        }catch (Exception $e) {
            return redirect('login/google');
        }

        $authUser = $this->CreateUser($user);
        Auth::login($authUser, true);
        return redirect()->route('home');
    }

    public function CreateUser($user)
    {
        $authUser = User::where('email', $user->email)->first();
        if ($authUser) {
            return $authUser;

        }
        return User::create([
            'name'     => $user->name,
            'email'    => $user->email,
        ]);
    }

    public function showLoginForm(){
        return view('auth.login')->withTitle('Login');
    }

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

Step 9 - Add routes for Google Login

Now routes for this controller functions should be added to call from a button click later. So, open routes/web.php file and add these 2 routes to it.

Route::get('login/google', 'Auth\LoginController@redirectToGoogleProvider')->name('glogin');
Route::get('login/google/callback', 'Auth\LoginController@handleGoogleProviderCallback')->name('gcallback');

Ok... Now we are ready to call the login/google function to load gmail sign up.

Step 10 - Add the Google Sign in button to login page

The login page should be modified. Replace it with this login page 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">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </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{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col-md-6 offset-md-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> {{ __('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 btn-md" style="margin-left: 0px;">
                                    SIGN IN
                                </button>
                                <a href="/login/google"><img src="http://www.setyourowntests.com/_/rsrc/1468869481521/help/accounts/btn_google_signin_dark_normal_web%402x.png" style="width: 190px; height: 42px;"></a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Output Login page :


We have completed the view also. We are ready to go!!!! First Logout from your Gmail account to see this properly. Then click on Google Signin button..You will be prompted to enter the gmail credentials. Enter them. After you enter the password and click on next, you will be directed to home page.


Data will be stored in your database automatically. Look at the below demo...


Congratulations Guys! Now you have created a decent Google Sign up process! Isn't it easy and nice? This is another application of Laravel. This amazing framework always makes our work easy..So, I invite you to create this kind of login/signup and add to your projects..

Good Luck!



8 Comments

  1. Laravel Development Company, Laravel is among the best PHP-based web app framework that is free and open-source. We offers a robust team of Laravel developers and programmers offering high-end and reliable solutions at highly-competitive rates. Contact us : +91-9806724185 or Contact@expresstechsoftwares.com

    ReplyDelete