Auth laravel error with another model?

2

Personally I changed the default model name of Laravel User.php to Colaboradores.php (of course, I set the $table and $primaryKey in the 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'));
}
    
asked by anonymous 21.05.2017 / 00:12

1 answer

3

When using another class that does not follow the same pattern of field names, there are ways to authenticate the user, by the instance of that class or by the user id as described in < a href="https://laravel.com/docs/5.4/authentication"> 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 attempt method should follow the same naming of names that are email and password in your table is different from your model authentication always will return false .

A tip: If not needed, do not change the default template, because it can even add new fields and relationships, and this ensures that all methods proposed in documentation works as it should.

References:

21.05.2017 / 01:45