I am trying to setup google login using socialite in laravel. But when I enter the google credentials, it shows 'The page isn’t redirecting properly' for the url http://127.0.0.1:8000/redirect/google
My web.php is:
Route::get('/redirect/google', 'SocialAuthController@redirect');
Route::get('/callback/google', 'SocialAuthController@callback');
services.php:
'google' => [
'client_id' => '-----.apps.googleusercontent.com',
'client_secret' => '---------',
'redirect' => 'http://127.0.0.1:8000/callback/google'
],
SocialAuthController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\SocialAccountService;
use Socialite;
class SocialAuthController extends Controller
{
//
public function redirect(){
return Socialite::driver('google')->redirect();
}
public function callback(SocialAccountService $service){
$user = $service->createOrGetUser(Socialite::driver('google')->user());
auth()->login($user);
return redirect()->back();
}
}
SocialAccount.php :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SocialAccount extends Model
{
//
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Migration for social_accounts_table
class CreateSocialAccountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('social_accounts', function (Blueprint $table) {
$table->increments('user_id');
$table->string('provider_user_id');
$table->string('provider');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('social_accounts');
}
}
SocialAccountService.php
<?php
namespace App;
use Laravel\Socialite\Contracts\User as ProviderUser;
class SocialAccountService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'role' => 'user',
'password' => '',
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
via Lakshya Garg