Skip to content
Advertisement

Laravel Input Validaiton Exists with username or email

how to make correct validation if i have input from where i can sign in with username or email, i want to if user will text username in field, it check if this username doesnt exist, then fail, also if he will choose to use email to sign in, then it will check if email doesnt exist then fail. (login form have only 2 inputs, login and password, in login u can text username or email)

my rule =

public function rules()
{
    return [
        'user'                => 'required|min:3|exists:users,username,email]',
        'password'            => 'required',
    ];
}

Advertisement

Answer

You can use custom login as :

public function login(Request $request)
{
    $request->validate([
        'user'                => 'required|min:3]',
        'password'            => 'required',
    ]);
}

$userName_or_Email = $request->user;
$password = $request->password;
$user = User::where('username',$userName_or_Email)->first();

if(empty($user)){
  $user = User::where('email',$userName_or_Email)->first();
}

if(empty($user)){
  return new Response()->with('error','Username or email not available in database');
}

if(Hash::check($password, $user->password)){
   // Login successful code
}else{
  return new Response()->with('error','Username or email not available in database');
}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement