Google oAuth with socialite in Laravel 5.3

Install socialite

composer require laravel/socialite

 

Register Laravel\Socialite\SocialiteServiceProvider in your config/app.php under providers

'providers' => [
...
Laravel\Socialite\SocialiteServiceProvider::class,

 

Add socialite class into config/app.php under aliases

'aliases' => [
...
'Socialite' => Laravel\Socialite\Facades\Socialite::class,

 

Create Facebook apps API @ https://developers.facebook.com

Create Google apps API @ https://console.developers.google.com

 

Add Facebook API credentials in config/services.php

'facebook' => [
'client_id' => '',
'client_secret' => '',
'redirect' => 'http://abc.com/auth/facebook/callback', //This must be same as your API callback address
],

'google' => [
'client_id' => '',
'client_secret' => '',
'redirect' => 'http://abc.com/auth/google/callback', //This must be same as your API callback address
],

Alternatively

'google' => [
'client_id' => env('GOOGLE_ID'),
'client_secret' => env('GOOGLE_SECRET'),
'redirect' => env('GOOGLE_REDIRECT')
],

 

Add routes

Route::get('auth/google', 'Auth\RegisterController@google';); 
Route::get('auth/google/callback', 'Auth\RegisterController@googleCallback';);

 

Add namespace to your app/Http/Controllers/Auth/RegisterController and two functions redirect() & googleCallback()

use Laravel\Socialite\Facades\Socialite as Socialite;

public function google() {

return Socialite::driver('google')->redirect();
}



public function googleCallback() {
try{
$google = Socialite::driver('google')->user();
}catch(Exception $e){
return redirect('/');
}

$user = User::where('google_id', $google->getId())->first();

if(!$user){
$user = User::create([
'google_id' => $google->getId(),
'name' => $google->getName(),
'email' => $google->getEmail(),
'password' => bcrypt($google->getId()),
'profile_pic' => $google->getAvatar(), ]);
}


auth()->login($user);
#return redirect()->to('/home');
return redirect()->intended('/');
}

 

 

Modify User model $fillable to below

protected $fillable = [ 
'name', 'email', 'password', 'profile_pic', 'google_id',
];

 

Change your database table schema for User table 

/database/migrations/create_users_table.php

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('profile_pic');
$table->string('google_id');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}

 

Run migration to apply new changes to database

php artisan migrate:refresh

 

Add login to view page

<a href="{{ url('/auth/google') }}">Social Login Google</a>

Finally clear and test

php artisan config:clear

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top