Laravel Auth::Atempt() always returns false

Asked

Viewed 575 times

4

I tried to authenticate, but it always comes back false in the method Auth::attempt() of Laravel:

$prontuario = Input::get('prontuario');
$senha = Input::get('senhas');  
if (Auth::attempt(['prontuario' => $prontuario, 'senha' => $senha]))
{ 
    return Redirect::to('/perfil');
}
else
{
    return Redirect::to('/')->withErrors('Prontuario ou senha inválidos!');
}

Passwords inserted in the database are already hashed, but still returns false in the condition if and I can’t log in. What’s left to work?

  • I made an answer, but, I also need to see how your class is User, you made changes, how is it? What is also the version of Laravel?

1 answer

5


The default way to authenticate follows a field pattern e-mail and password (respectively on the table users: email and password), as demonstrated on the link and on that other link.

The ideal and standard code would be this:

if (Auth::attempt(['email' => $email, 'password' => $password])) {
     // Authentication passed...
     return redirect()->intended('dashboard');
}

Outside this pattern is possible also as for example an instance of class User:

$user = User::find(1);
if ($user)  // encontrou o usuário
{
    Auth::login($user); // autentica o usuário
}

do user search by bringing an instance of class User and step in the method Auth::login($user) and is also made the authentication.

In your specific case I could observe that you do not follow a pattern, so you should use the form of instance:

$prontuario = Input::get('prontuario');
$senha = Input::get('senhas');  

$user = User::where('prontuario', $prontuario)
            ->first(); // buscando um registro desse pontuário

if ($user) // encontrou o usuário
{
   if (Hash::check($senha, $user->senha)) // conferindo senha
   {
       Auth::login($user); // autentica o usuário
   }
   else
   {
       //senha inválida...
   }
}
else
{
   return Redirect::to('/')->withErrors('Prontuario ou senha inválidos!');
}   

There is also a factor, the authentication of follows a pattern from a table Users and a class of User, if there has been change in this should be careful to change in all parts so that your code does not break, ie it is possible to change the table and the model for authentication, but this code should reflect in the settings of the and that will depend on the version.

  • 2

    Perfect, I did as you passed and it worked. Dude, I’m having a hard time with this MVC scheme. I haven’t been taught in college yet and the teacher is already charging high knowledge base for the final project... But I thank you for your help Virgilio!

  • 2

    I think no college teaches development, it’s a lot of theory and a lot of practice, and the teachers still think they’re right, I believe that the education system is very obsolete. But being didactic is my motto!

Browser other questions tagged

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