2
I have a login form where I have the fields "username" and "password". The difficulty I have been finding is the following: I want to give the option of the user to log in by CPF, email or phone (in the "username" field). Since in the Attempt() method of the Auth() class, which I use to authenticate, I can only pass values that reference fixed columns. See how my code is in the login method:
public function login(Request $request){
$array = ["error" => ''];
$username = $request->input('username'); //Será passado o email,cpf ou telefone
$password = $request->input('password');
if($user && $password){
$token = Auth()->attempt(['email' => $username, 'password' => $password]);
if(!$token){
return $this->unauthorized();
}
$array['token'] = $token;
}
}
Above, that $username variable can be Cpf, email, or phone (which are distinct columns from the users table).
In short, I want to give the opportunity for the user to log in with the option he wants between these 3 (Cpf, email and phone).
Roughly, just to illustrate my need, it would be something like this:
$token = Auth()->attempt(['email/cpf/phone' => $username, 'password' => $password]);
Could you help me with that ? If I am not clear, let us know in the comments that I edit and add information.
OBS: I’m wearing Laravel 7.
If you have a way fully deterministic to differentiate
email
ofcpf
and ofphone
provided by the user, you can dynamically set the first key of the associative array. Otherwise, the most ideal is to mount the query manually and, after validating the authentication, log the user using the methodlogin
(orsetUser
), see the API. I don’t know much about Laravel (I’ve never used it, but I think it’s the same method). Anyway, this is the idea, I hope I made it clear. :) [...]– Luiz Felipe
looking at the documentation here I see no other way to do it than by retaining the call from Attempt, ex if(Auth()->Attempt(['email' => $username, 'password' => $password] || Auth()->Attempt(['Cpf' => $username, 'password' => $password]);
– Lucas Miranda
@Lucasmiranda, puts, I looked at the doc to hell too. I wanted to avoid the maximum does that. I would only do so if there was no other alternative.
– Gato de Schrödinger
@Luizfelipe , then, I asked the question more in order to know if there is something in the Lake that I use specifically for this, without making possible "juggling". If I don’t, I’ll look for alternatives like the ones you and Lucas mentioned.
– Gato de Schrödinger