Google login in laravel

To build a login with a Google account in the Laravel system, we need to have a Gmail email account. This gmail account will help us to create an account with the Google developer console. In the developer console, we can grant access to create the Google client id and client secret.

composer require laravel/socialite
https://console.cloud.google.com/welcome?project=pure-lantern-377411

Now create your project. Goto to this bellow link.
https://console.cloud.google.com/apis/dashboard?project=pure-lantern-377411

Now goto to credientials at the left sidebar.
Click on create credientials & choose create oauth client id.
Click on configure conset screen.
Check on external option and create option.
Fill oauth name fileld, user support email which is same as your google account & developer contact information. CLick save and continue.
Click again crediential link on left sidebar.
Create crediential again and choose oauth client id option.

Application type
Name
URL (localhost or domain)
Rediect url.

Click on create button.

client id:  185998463453-nsbnpl9d8gh4i5kkgosmmh209cu25354.apps.googleusercontent.com
client secret: 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
.env

GOOGLE_CLIENT_ID = 185998463453-nsbnpl9d8gh4i5kkgosmmh209cu25354.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET = 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
config/services.php

'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => 'http://127.0.0.1:8000/google/callback',
],
config/app.php

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

'aliases' => [
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
Create Google login link suppose: {{route('google_login')}}

<a href="{{route('google_login')}}" class="btn btn-primary">Google Login</a>
Route::get('google-login', [Crudcontroller::class, 'google_login'])->name('google_login');
Route::get('/google/callback', [Crudcontroller::class, 'google_callback'])->name('google_callback');
Controller:

use Laravel\Socialite\Facades\Socialite;

function google_login(Request $req){
return Socialite::driver('google')->redirect();
}
Controller:

function google_callback(Request $req){
try{
$user = Socialite::driver('google')->user();
$findUser = User::where('email', $user->email)->first();

if(!$findUser){
User::create([
'name' => $user->name, 
'email' => $user->email,
'password' => Hash::make($user->email) 
]); 

if(Auth::attempt(['email' => $user->email, 'password' => $user->email])){ $user->session()->regenerate(); 
return redirect('dashboard')->withSuccess('You have successfully registered & logged in!'); 
}
}
else{
if(Auth::attempt(['email' => $user->email, 'password' => $user->email])){ $user->session()->regenerate(); 
return redirect('dashboard')->withSuccess('You have successfully registered & logged in!'); 
}

}
}
catch(Exception $e){
dd($e->getMessage());
}
}

Leave a Reply