Laravel 社交名流用户创建验证?

问题描述 投票:0回答:1

我试图用 Laravel 实现社交名流登录注册。但我无法使用 Laravel 默认验证规则验证数据。就像在用户表中一样,电子邮件应该是唯一的。我如何用现有代码实现?

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{

                $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());
        }
    }
php laravel laravel-validation
1个回答
0
投票

如果我要使用 Laravel

Validator
来处理你的情况,我会这样做:


<?php

use 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|unique:users|max:255'
                ]
            );
    
            if ($validator->fails()) {
                throw new \Exception("Validation error");
            }
            
            $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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.