Laravel 12 Socialite Login với tài khoản google
Hôm nay mình sẽ hướng dẫn các bạn đăng nhập vào website với google account
1 Cài đặt laravel 12
Chúng ta tạo với lệnh :
composer create-project laravel/laravel la12gmail
2 Cài đặt Socialite
Cài đặt Socialite với composer sau :
composer require laravel/socialite
3 Tạo Google App
Go to https://console.cloud.google.com/projectcreate and create a new project.
Bây giờ vào https://console.cloud.google.com/apis/credentials/consent và tạo
Tiếp theo trong GoogleController :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Laravel\Socialite\Facades\Socialite;
use Exception;
class GoogleController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
/**
* Create a new controller instance.
*
* @return void
*/
public function handleGoogleCallback()
{
try {
$user = Socialite::driver('google')->user();
if (!$user->email) {
return redirect()->route('login')->with('error', 'Google không cung cấp email. Vui lòng đăng ký bằng email.');
}
// Log::info('User Data:', (array) $user); // Kiểm tra dữ liệu nhận được từ Google
$finduser = User::where('google_id', $user->id)->first();
if ($finduser) {
Auth::login($finduser);
$finduser->userinfo()->updateOrCreate(
[], // Điều kiện kiểm tra (không cần điều kiện vì HasOne chỉ có 1 bản ghi)
['avatar' => $user?->getAvatar() ?? '']
);
return redirect()->intended(route('home'));
} else {
$newUser = User::updateOrCreate(['email' => $user->email], [
'name' => $user->name,
'google_id' => $user->id,
'password' => encrypt(env('KEY_PASSWORD_MACDINH'))
]);
Log::info($user?->avatar);
$newUser->userinfo()->updateOrCreate(
[], // Điều kiện kiểm tra (không cần điều kiện vì HasOne chỉ có 1 bản ghi)
['avatar' => $user?->getAvatar() ?? '']
);
Auth::login($newUser);
return redirect()->intended(route('home'));
}
} catch (Exception $e) {
Log::error('Google Login Error: ' . $e->getMessage());
return redirect()->route('login')->with('error', 'Đăng nhập bằng Google thất bại.');
}
}
}
Ở đây chúng ta tạo 1 bảng để lưu các thông tin Userinfo để lưu thông tin ảnh
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements \Illuminate\Contracts\Auth\MustVerifyEmail
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable,HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
'status',
'google_id',
'github_id',
'facebook_id',
];
public function userinfo(){
return $this->hasOne(Userinfo::class,'user_id','id');
}
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
Trong route :
Route::controller(\App\Http\Controllers\Auth\GoogleController::class)->group(function () {
Route::get('auth/google', 'redirectToGoogle')->name('auth.google');
Route::get('auth/google/callback', 'handleGoogleCallback');
});
Oke vây là xong