Check which field already exists in the table

Asked

Viewed 400 times

4

I’m 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 mostly out of curiosity. You can tell which of the fields entered the SELECT condition ?

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

1 answer

3


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

If you are using Laravel 5+, check the validation rules in your AuthController, let 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 any 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 by checking 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');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.