1. Tạo ứng dụng trong Google Console Developer để lấy mã key xác thực
Vào trang http://console.developers.google.com/ --> tạo ứng dụng mới --> vào phần APIs & Service để tạo Credentials
Tiếp theo vào file config/services.php để tạo cấu hình
return [
....
'google' => [
'client_id' => 'app id',
'client_secret' => 'add secret',
'redirect' => 'http://localhost:8000/auth/google/callback',
],
]
Tiếp theo: Trong bảng dữ liệu users, thêm 1 cột là google_id và trong model thêm cột đó vào biến $fillable
Tiếp theo trong routes tạo ra 2 cái link để điều hướng
Route::get('auth/google', [GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
Tiếp theo trong Controller xử lý đăng nhập, thêm 2 hàm sau:
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback()
{
try {
$user = Socialite::driver('google')->user();
$finduser = User::where('google_id', $user->id)->first();
if($finduser){
Auth::login($finduser);
return redirect()->intended('dashboard');
}else{
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'google_id'=> $user->id,
'password' => encrypt('123456dummy')
]);
Auth::login($newUser);
return redirect()->intended('dashboard');
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
Cuối cùng là thêm nút bấm vào giao diện màn hình đăng nhập
<a href="{{ url('auth/google') }}">
<img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png" style="margin-left: 3em;" />
</a></code>
OK, đến bước chạy thử.