Login with Google Via Laravel 5.6

25083 views 4 years ago Laravel

Today, I am going to show you guys how to login in google using laravel 5.2. Before processing login into google, you must need google API key, Client ID and Client secret key. You can get these credentials from google if you dont have now.

[ADDCODE]

By following six steps given below you will be able to register on google via laravel.

Step 1: Laravel 5.6 Instalation.

Follow this step if laravel is not installed in your system. If you already have the laravel project setup than you can jump to the second step directly.


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

Step 2: Generate users table and model

To crate a User table in your database, you just need to fire some PHP artisan commands it will generate migration file for user table in the migration folder of your project setup. You can use below commands to generate user table mgration.


php artisan make:migration create_users_table

Above command will generate a migration file in database/migrations folder. Now just put the below given code to create a user table in your database.


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::drop('users');
    }
}

Save the file and fire following commands.


php artisan migrate

above command will generate a user table in the database.

Now create a new model named User.php as shown below.

Step : 3 make change in app/User.php

namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Step3: Update Composer File to add Google apiclient libraries

Put following line in your composer file and update your composer to download package:


"google/apiclient": "2.0.*"

Step4: Route File

Now add following routes in your routes.php


Route::get('glogin',array('as'=>'glogin','uses'=>'[email protected]')) ;
Route::get('google-user',array('as'=>'user.glist','uses'=>'[email protected]')) ;

Step5: User Controller

Now create User Controller file in following path app/Http/Controllers/

app/Http/Controllers/UserController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
class UserController extends Controller
{
    public function googleLogin(Request $request)  {
        $google_redirect_url = route('glogin');
        $gClient = new \Google_Client();
        $gClient->setApplicationName(config('services.google.app_name'));
        $gClient->setClientId(config('services.google.client_id'));
        $gClient->setClientSecret(config('services.google.client_secret'));
        $gClient->setRedirectUri($google_redirect_url);
        $gClient->setDeveloperKey(config('services.google.api_key'));
        $gClient->setScopes(array(
            'https://www.googleapis.com/auth/plus.me',
            'https://www.googleapis.com/auth/userinfo.email',
            'https://www.googleapis.com/auth/userinfo.profile',
        ));
        $google_oauthV2 = new \Google_Service_Oauth2($gClient);
        if ($request->get('code')){
            $gClient->authenticate($request->get('code'));
            $request->session()->put('token', $gClient->getAccessToken());
        }
        if ($request->session()->get('token'))
        {
            $gClient->setAccessToken($request->session()->get('token'));
        }
        if ($gClient->getAccessToken())
        {
            //For logged in user, get details from google using access token
            $guser = $google_oauthV2->userinfo->get();  
                $request->session()->put('name', $guser['name']);
                if ($user =User::where('email',$guser['email'])->first())
                {
                    //logged your user via auth login
                }else{
                    //register your user with response data
                }               
         return redirect()->route('user.glist');          
        } else
        {
            //For Guest user, get google login url
            $authUrl = $gClient->createAuthUrl();
            return redirect()->to($authUrl);
        }
    }
    public function listGoogleUser(Request $request){
      $users = User::orderBy('id','DESC')->paginate(5);
     return view('users.list',compact('users'))->with('i', ($request->input('page', 1) - 1) * 5);;
    }
}

Step 6: Create Laravel Blade File to list User who login with google

@extends('layouts.default') 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Logged Google User List</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-danger" href="{{ route('glogin') }}"> Login with Google</a>
            </div>
        </div>
    </div>
    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Login Time</th>
        </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ ++$i }}</td>
        <td>{{ $user->name }}</td>
        <td>{{ $user->updated_at->diffForHumans() }}</td>   
    </tr>
    @endforeach
    </table>
    {!! $users->render() !!}
@endsection

To get client_id, client_secret and api_key you have to create a app within google console and generate these tokens.

Now this code is ready to use in your application for google login and register in Laravel 5.2.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]