php – Check which field already exists in the table


I'm doing a query in Laravel to see if the user with the typed e-mail, CPF or username already exists in the database.

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

It's more out of curiosity. Is it possible to know which of the fields entered the SELECT condition?

If it is the e-mail, CPF or username that already exists?


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

If you are using Laravel 5+, check the validation rules in your AuthController , make 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 when registering.

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

$verUser = User::whereEmail($email)


    $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');
Scroll to Top