HDTuto.com

Laravel 5.6 - Login with Google with Socialite


Hi Developer,

In this example, I will let you how to login with google account on your laravel website. in this example I will use Socialite composer package for sign in with google gmail account. so just follow bellow all step for auth with google in you laravel application. Laravel 5.6 provide us Socialite package that is help to social authentication. Let's follow bellow step:

Step 1: Install Socialite Package

In first step we will install Socialite Package that provide google api to connect with google. So, first open your terminal and run bellow command:

composer require laravel/socialite

After install above package we should add providers and aliases in config file, Now open config/app.php file and add service provider and alias.

config/app.php

'providers' => [

....

Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [

....

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

],

Step 2: Create Google App

In this step we need google app id and secret that way we can get information of other user. so if you don't have google app account then you can create from here : https://console.developers.google.com and after create account you can copy client id and secret.

Now you have to set app id, secret and call back url in config file so open config/services.php and .env file then set id and secret this way:

config/services.php

return [

....

'google' => [

'client_id' => env('GOOGLE_CLIENT_ID'),

'client_secret' => env('GOOGLE_CLIENT_SECRET'),

'redirect' => env('GOOGLE_CALLBACK_URL'),

],

]

.env

GOOGLE_CLIENT_ID=xxxxxxxxx

GOOGLE_CLIENT_SECRET=xxxxxxx

GOOGLE_CALLBACK_URL=http://localhost:8000/auth/google/callback

Step 3: Create Migration and Model

In this step first we have to create migration for add google_id in your user table. so let's create new migration and bellow column this way:

Migration:

<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class AddNewColunmUsersTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::table("users", function (Blueprint $table) {

$table->string('google_id');

});

}


/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::table("users", function (Blueprint $table) {

$table->dropColumn('google_id');

});

}

}

Here Add 10

Now add addNew() in User model, that method will check if google id already exists then it will return object and if not exists then create new user and return user object. so open user model and put bellow code:

app/User.php

<?php


namespace App;


use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;


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',

];


public function addNew($input)

{

$check = static::where('google_id',$input['google_id'])->first();


if(is_null($check)){

return static::create($input);

}


return $check;

}

}

Step 4: Create New Routes

In this step we need to create routes for google login, so you need to add following route on bellow file.

routes/web.php

Route::get('google', function () {

return view('google');

});

Route::get('auth/google', 'Auth\GoogleController@redirectToGoogle');

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

Step 5: Create New GoogleController

we need to add new controller and method of google auth that method will handle google callback url and etc, first put bellow code on your GoogleController.php file.

app/Http/Controllers/Auth/GoogleController.php

<?php


namespace App\Http\Controllers\Auth;


use App\User;

use App\Http\Controllers\Controller;

use Socialite;

use Exception;

use Auth;


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();

$create['name'] = $user->getName();

$create['email'] = $user->getEmail();

$create['google_id'] = $user->getId();


$userModel = new User;

$createdUser = $userModel->addNew($create);

Auth::loginUsingId($createdUser->id);


return redirect()->route('home');


} catch (Exception $e) {


return redirect('auth/google');


}

}

}

Step 6: Create Blade File

Ok, now at last we need to add blade view so first create new file google.blade.php file and put bellow code:

resources/views/google.blade.php

@extends('layouts.app')


@section('content')

<div class="container">

<div class="row">

<div class="col-md-12 row-block">

<a href="{{ url('auth/google') }}" class="btn btn-lg btn-primary btn-block">

<strong>Login With Google</strong>

</a>

</div>

</div>

</div>

@endsection

Ok, now you are ready to use open your browser and check here : URL + '/google'.

I hope you found your best solution....




April 7, 2018 | Category : PHP Laravel Laravel 5 Laravel 5.5 Laravel 5.6
Related Posts