Laravel Socialite用户创建验证:邮箱唯一性校验实现问题
你可以通过两种方式把邮箱唯一性校验嵌入到现有代码中:
方式一:手动使用Laravel Validator验证
在创建新用户前,先对第三方返回的邮箱做唯一性校验,根据校验结果处理后续流程:
修改你的callbackToGoogle方法:
use Illuminate\Support\Facades\Validator; public function callbackToGoogle(Request $request) { try { $user = Socialite::driver('google')->user(); $finduser = User::where('gauth_id', $user->id)->first(); if($finduser){ Auth::login($finduser); return redirect('/home'); } else { // 验证邮箱唯一性 $validator = Validator::make( ['email' => $user->email], ['email' => 'required|email|unique:users,email'] ); if ($validator->fails()) { // 邮箱已存在,可根据需求跳转提示,比如返回登录页 return redirect('/login')->withErrors(['email' => '该邮箱已被注册,请直接登录']); } $newUser = User::create([ 'first_name' => $user->offsetGet('given_name'), 'last_name' => $user->offsetGet('family_name'), 'email' => $user->email, 'gauth_id'=>$user->id, 'gauth_type'=>'google', 'password' => encrypt('admin@123') ]); Auth::login($newUser); return redirect('/home'); } } catch (Exception $e) { dd($e->getMessage()); } }
方式二:通过模型事件自动验证
如果希望所有用户创建操作都自动校验邮箱唯一性,可以在User模型中添加creating事件:
在app/Models/User.php中添加:
use Illuminate\Database\Eloquent\Events\Creating; use Illuminate\Support\Facades\Validator; protected static function booted() { static::creating(function ($user) { $validator = Validator::make( ['email' => $user->email], ['email' => 'required|email|unique:users,email'] ); if ($validator->fails()) { throw new \Illuminate\Validation\ValidationException($validator); } }); }
此时无需修改回调方法,当执行User::create()时会自动触发验证。你可以在catch块中捕获验证异常并处理:
catch (\Illuminate\Validation\ValidationException $e) { return redirect('/login')->withErrors($e->validator->errors()); } catch (Exception $e) { dd($e->getMessage()); }
额外优化:关联已有邮箱账号
如果遇到邮箱已存在但未绑定谷歌登录的情况,可直接将当前谷歌账号与已有用户绑定:
// 替换验证失败后的逻辑 if ($validator->fails()) { $existingUser = User::where('email', $user->email)->first(); // 绑定谷歌账号信息 $existingUser->update([ 'gauth_id' => $user->id, 'gauth_type' => 'google' ]); Auth::login($existingUser); return redirect('/home'); }
内容的提问来源于stack exchange,提问作者Hola
相关产品推荐
相关产品推荐

