Customizing a user model Laravel 5.4 - Login problem

Asked

Viewed 4,876 times

7

I tried everything already, but I can’t solve a problem in the login system Laravel which is this: I created a model called Usuarios, I put all the information in it that has to be properly placed, like the array $fillable and $hidden, however, internally the Laravel still treats as model login pattern to User model, I managed to change this, through this line:

protected $table = 'Usuarios';

Another problem has arisen, of not finding the field password that was standard (default), I went to the archive EloquentUserProvider and changed from password for Senha (which is how it is in I bank. However now it does not pass in the Auth::attempt(). I spent all day looking for some solution, all I tried was in vain).

Model code User:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $model = 'Usuario';
    protected $increments = false;
    protected $table = 'Usuarios';
    protected $primaryKey = 'UsuarioID';

    public function getAuthIdentifier() {
        return $this->getKey();
    }

    public function getAuthPassword() {
        return $this->Senha;
    }

    public function getReminderEmail() {
        return $this->Login;
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Model code Usuario:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Usuario extends Authenticatable
{
    use Notifiable;

    /*protected $model = 'Usuario';
    protected $increments = false;
    protected $table = 'Usuarios';
    protected $primaryKey = 'UsuarioID';

    public function getAuthIdentifier() {
        return $this->getKey();
    }

    public function getAuthPassword() {
        return $this->Senha;
    }

    public function getReminderEmail() {
        return $this->Login;
    }*/

    protected $fillable = [
        'UsuarioID', 'Nome', 'Login', 'Senha'
    ];

    protected $hidden = [
        'Senha', 'remember_token',
    ];
}

Code of function logging into controller:

public function entrar(Request $request)
{
    $dadosFormulario=$request->all();
    $dadosLogin=['Login'=>$dadosFormulario['login'],'Senha'=>$dadosFormulario['senha']];

    if( dd(Auth::attempt($dadosLogin)) ){
        return redirect()->route('admin.cursos');
    } else {
        return redirect()->route('site.home');
    }
}

Here I have already checked if the data is coming from the form correctly and any help is welcome.

  • I ask: Why change? , for this to work you don’t need to change the base class and authentication can be done differently...

  • Virgil, where exactly do I put the code of step 5?

  • @Eriksonflávio puts in action controller that will be responsible for logging the user.

1 answer

10


Observing: You don’t need to change anything that comes in framework of the briefcase vendor which is the core, if there have been changes back to what was.

Step by step:

Bench

1) Creation of Model Usuarios

<?php namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Usuarios extends Authenticatable
{
    use Notifiable;

    protected $fillable = ['Nome', 'Login', 'Senha'];
    protected $hidden = ['Senha', 'remember_token'];
    protected $primaryKey = 'UsuarioID';
    protected $table = "usuarios";
    
}

2) Migration Model Usuarios

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Usuarios extends Migration
{
    public function up()
    {
        Schema::create('usuarios', function (Blueprint $table) {
            $table->increments('UsuarioID');
            $table->string('Nome');
            $table->string('Login')->unique();
            $table->string('Senha');
            $table->rememberToken();
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('usuarios');
    }
}

3) Changing the file configuration config\auth.php in the key providers, informing the new class that will be responsible for authentication:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Usuarios::class,
    ],

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

4) Manual creation of table records Usuarios:

$usuario = Usuarios::create(array(
    'Nome' => 'StackOverFlow',
    'Login' => '[email protected]',
    'Senha' => bcrypt('stack')
));

5) To log in with the information contained in the table Usuarios:

$usuario = Usuarios::where('Login', '[email protected]')
                   ->first();

if (Hash::check('stack', $usuario->Senha))
{
    Auth::loginUsingId($usuario->UsuarioID);
}

That’s the five steps to autenticar in an application through a particular code and the natural process has to be changed to these 5 steps including when logging into the system.

References:

  • I did all this, the errors are gone, but it does not pass in Auth::Attempt(), it always returns false. Here the method code public function entrar(Request $request)&#xA; {&#xA; $dados = $request->all();&#xA; $usuario = Usuario::where('Login', $dados['login'])->first();&#xA; dd($usuario);&#xA; if(Auth::login($usuario)){&#xA; return redirect()->route('admin/cursos');&#xA; } else {&#xA; return 'não entrou no attempt';&#xA; }&#xA;&#xA; }

  • PS:I already tried with Auth::Attempt() too, and also returns me null . Below the config/auth&#Xa code;'providers' => [&#xA; 'users' => [&#xA; 'driver' => 'eloquent',&#xA; 'model' => App\Usuario::class,&#xA; ],&#xA; ],

  • @Matheuspicioli is not Auth::attempt() is Auth::loginUsingId($usuario->UsuarioID); if you saw in the answer... Only one thing, besides the knowledge I already have of the framework, this answer that is not very usual is a real fact, tested and functional, tells me which error happens?

  • @@Edit@@ Sorry for my inattention, I forgot to change the comparison field, however now it returns me this error Operand type clash: uniqueidentifier is incompatible with int (SQL: select top 1 * from [Usuarios] where [Usuarios].[UsuarioID] = 86866388 Something like the ID he brought is not being a GUID

  • Where are you giving this trouble? @Matheuspicioli ?

  • When I call the enter method, it is returning this error: QueryException in Connection.php line 647:&#xA;SQLSTATE[22018]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Operand type clash: uniqueidentifier is incompatible with int (SQL: select top 1 * from [Usuarios] where [Usuarios].[UsuarioID] = 84)

  • I got the error because I was looking at the GUID as an INTEGER, and I thought I had put the $incrementing = false on the User model, but I wrote it wrong, it was $increments. Thank you for your patience and cooperation.

  • 1

    yes, I did. Thank you very much!

  • I would like to understand the negative vote, because, has no problems in the answer or has?

  • 1

    I did not vote against, I put as my best answer.

  • 1

    And it worked perfectly

  • @Matheuspicioli is not you are some other user who did not like the answer, but did not give a reason to vote negative. But that’s okay!

  • Ah, yes, I get it. If you can give us a little more help: http://answall.com/questions/188405/como-enviaruma-imagem-din%C3%A2mica-para-o-php-com-a-fun%C3%A7%C3%A3o-ajax-do-jquery

  • @Virgilionovic because he stopped using Auth::Attempt($dadosLogin) ??

  • @Milrakpereirapessoa he changed the class that made the authentication and the method attemp authenticates through two standard fields which is email and password, already his class does not have these fields so Laravel opens an alternative as explained in this answer!

  • 1

    This way then we can not use attemp, because we will not be using the standard email and password fields, now it is clear why we should use another way to authenticate. Thanks for the @Virgilionovic explanation

Show 11 more comments

Browser other questions tagged

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