Laravel Socialite User Creation Validation?

38 views Asked by At

I was trying to implement socialite login register with Laravel. But i failed to validate data with laravel default validation Rule. Like in user table , email should be unique. How can i implement with existing code?

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());
        }
    }
1

There are 1 answers

0
Arigi Wiratama On

If I'm going to use Laravel Validator for your case, I will do it like this:


<?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());
    }
}