Laravel 5.8 Google Socialite Authentication

Ikechukwu Chidera
Mar 17 · 5 min read

Welcome back guys…

Here, I’ll be out-listing step by step procedures of successfully integrating Google authentication using Socialite in your Laravel blog.

NOTE: You can also check for Laravel 5.8 Facebook Socialite Authentication here.

I’ll be making use of images to accurately illustrate and guide you through. All codes needed for the integration are also included here.

Now, let’s get started…

STEP 1: Open your Laravel blog in Terminal(for Linux users) or Git Bash(for Windows users) and run the laravel migration command using:

php artisan migrate

Also, run the laravel authentication command using:

php artisan make:auth

This command will automatically update your route files and set up Login and Registration dashboard on your laravel welcome page.

STEP 2: Next, we download the laravel/socialite package using this command:

composer require laravel/socialite

After this, we need to set up configurations for our Socialite package.

We do this by going to “app.php” inside “config” folder and insert the following codes.

In “app.php”, scroll down to ‘providers’ section and add Socialite service provider using:

Laravel\Socialite\SocialiteServiceProvider::class,

On the same page; “app.php”, also scroll down to ‘aliases’ and add this config:

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

Still on the socialite configurations, switch to “services.php” still inside the “config” folder, add this command:

'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT'),
],

Now we’re done with the configurations, let’s go to step 3…

STEP 3: Here, we create our Google app so that we can get a ‘client_id’ and ‘client_secret’ from Google.

We do this by going to Google’s developers URL: https://console.cloud.google.com/ and log in with your Google account.

Go to ‘My Projects’, proceed to ‘New Project’ as shown below…

Next, input your Product name and click on ‘Create’ as shown below…

Next, go to APIs & Services -> Credentials, click on Create credential and select OAuth Client Id as shown below…

Next, click on create consent screen, add Application name and click on ‘Save’ as shown below…

Then select Web Application and configure as shown below…

Click on Create and copy your Client_id and Client_secret.

We’re done with all App settings, now let’s go over to STEP 4.

STEP 4: Now got to your ‘.env’ file and update with these:

GOOGLE_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GOOGLE_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx
GOOGLE_REDIRECT=http://localhost:8000/callback

Remember to replace client_id and secret with those received from google.

Next, create a controller for laravel Google login…

php artisan make:controller SocialAuthGoogleController

In this controller, we’ll add two functions: redirect() function to redirect the user to Google and callback() function is used for handle user when callback from Google. To achieve this, we add the following codes to our controller:

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use Socialite;
use App\Services\SocialGoogleAccountService;
class SocialAuthGoogleController extends Controller
{
/**
* Create a redirect method to google api.
*
* @return void
*/

public function redirect()
{
return Socialite::driver('google')->redirect();
}
/**
* Return a callback method from google api.
*
* @return callback URL from google
*/

public function callback(SocialGoogleAccountService $service)
{
$user = $service->createOrGetUser(Socialite::driver('google')->user());
auth()->login($user);
return redirect()->to('/home');
}
}

Next we update our route; routes -> web.php using:

Route::get('/redirect', 'SocialAuthGoogleController@redirect');
Route::get('/callback', 'SocialAuthGoogleController@callback');

STEP 5: Now navigate to ‘resources’ -> ‘views’ -> ‘auth’ -> ‘login.blade.php’. Below the closing tag for <div class=”form-group”>,add the following codes:

<br />
<p style="margin-left:265px">OR</p>
<br />
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<a href="{{url('/redirect')}}" class="btn btn-primary">Login with Google</a>
</div>
</div>

These codes will add a button for Google login on your laravel login page.

Now let’s create a model and a table for our logged in google accounts. we use this command:

php artisan make:model SocialGoogleAccount -m

Now navigate to ‘app’ -> ‘SocialGoogleAccount.php’ and add these codes for our model…

<?php// SocialGoogleAccount.phpnamespace App;use Illuminate\Database\Eloquent\Model;class SocialGoogleAccount extends Model
{
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}

Next navigate to ‘database’ -> ‘migrations’ -> ‘create_social_google_accounts_table.php’ and add these codes…

<?php// create_social_google_accounts.phpuse Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSocialGoogleAccountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('social_google_accounts', function (Blueprint $table) {
$table->integer('user_id');
$table->string('provider_user_id');
$table->string('provider');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('social_google_accounts');
}
}

Also run the following command to refresh our database tables.

php artisan migrate:refresh

STEP 6: Here, we handle our authentication services, through which the users can be registered or login if user already exists.

This is how we do it:

We manually create a folder named ‘Services’ inside ‘app folder’, then create a file named ‘SocialGoogleAccountService.php’. We now add the following codes to our newly created file…

<?phpnamespace App\Services;
use App\SocialGoogleAccount;
use App\User;
use Laravel\Socialite\Contracts\User as ProviderUser;
class SocialGoogleAccountService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialGoogleAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialGoogleAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();if (!$user) {$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'password' => md5(rand(1,10000)),
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}

Hurray, we’ve successfully integrated Google login to our laravel blog.

Now run php artisan serve

and test the authentication process.

I hope the procedures are clear and understandable. Feel free to comment and ask questions where confused.

Also, don’t forget to give a ‘clap’ for this post. Thank you.