Error auth Lockable with another model?

Asked

Viewed 323 times

2

People changed the name of the standard model of Laravel User.php for Colaboradores.php (of course, I set the $table and the $primaryKey model), I also changed the config/auth.php to model. but login is always returning me false, follow login code:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Siga\Colaboradores::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

public function auth( Request $request )
{

    $username = $request->input("usuario_colaborador");
    $password = $request->input("senha_colaborador");

    if( Auth::check() || Auth::attempt([
        'usuario_colaborador' => $username,
        'senha_colaborador' => $password]) )
    {
        // redirecionando usuário depois de logado
        return redirect(route('farol.meufarol'));
    }
    else
        return redirect(route('login'));
}

1 answer

3


When using another class that does not follow the same field name pattern, there are ways to authenticate the user, by the instance of that class or by User Id as described in documentation.

The ideal code in this case would be to first bring this instance and check if the data is correct, as follows:

public function auth( Request $request )
{

    $username = $request->input("usuario_colaborador");
    $password = $request->input("senha_colaborador");

    //busca o usuário para ver se o mesmo existe
    $model    = Siga\Colaboradores::where('usuario_colaborador',$username)->first();

    // confere se o usuário é a mesma senha
    if( Auth::check() || 
      ($model && Hash::check($password, $model->senha_colaborador)) )
    {
        // redirecionando usuário depois de logado
        Auth::login($model); // autenticando ...
        return redirect(route('farol.meufarol'));
    }
    else
        return redirect(route('login'));
}

Basically these would be the changes, ie as the method attempt must follow the same nomenclature of names that are email and password on your table is different from your model authentication will always return false.

A tip: if not necessary, do not change the standard model, because it can even be added new fields and relationships, and this ensures that all methods proposed in the documentation work as it should.

References:

Browser other questions tagged

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