Check which field already exists in the table

4

I am making a query in Laravel to see if the user with the email, CPF or username entered already exists in the database.

# Verificar se Usuário Já Existe na Base de Dados
$verUser       = User::whereEmail($email)
                        ->orWhereCpf($cpf)
                        ->orWhereUsername($username)
                        ->first();
if($verUser){
    Session::flash('alert-error', 'Um usuário já existe na base de dados.');
    return redirect()->to('auth/login');
}

It's more out of curiosity. Can you tell which of the fields entered the SELECT condition?

If it is the email, CPF or username that already exists?

    
asked by anonymous 18.03.2016 / 13:21

1 answer

3

The easiest way to do this is to use the unique of Validator rule before registering your user.

If you are using Laravel 5+, check the validation rules in your AuthController , leave it look like this:

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'username' => 'required|unique:users',
        'cpf' => 'required|unique:users',   
        'password' => 'required|confirmed|min:6',
    ]);
}

So when there is a problem with these fields, Laravel will return a specific error message for each field at the time of registration.

Another way to do this is to check the return of each field:

$verUser = User::whereEmail($email)
              ->orWhereCpf($cpf)
              ->orWhereUsername($username)
              ->first();

if($verUser){

    $camposRepetidos = [];

    if ($verUser->username === $username) {
        $camposRepetidos[] = 'Username';
    }

    if ($verUser->cpf === $cpf) {
        $camposRepetidos[] = 'CPF';
    }

    if ($verUser->email === $email) {
        $camposRepetidos[] = 'E-mail';
    }

    $mensagem = 'Um usuário já existe na base de dados. 
                 Verifique os seguintes campos: ' . implode(',', $camposRepetidos);

    Session::flash('alert-error', $mensagem);
    return redirect()->to('auth/login');
}
    
20.03.2016 / 16:36