joaopedro489
joaopedro489

Reputation: 13

Auth::attempt always return false and I don't know why

public function login( Request $request ) {

        $fields = [
            'email' => $request->email,
            'password' => $request->password,
        ];

        $access = Auth::attempt( $fields );
      echo $access;
        if ( $access ) {

            $user = Auth::teacher();
            $token = $user->createToken('MyApp')->accessToken;

            return response()->json( [
                "message" => "Login realizado com sucesso!",
                "data" => [
                    'user' => $user,
                    'token' => $token
                ]
            ], 200 );

        } else {

            return response()->json( [
                "message" => "Email ou senha inválidos!",
                "data" => null,
                "return" => $access,
            ], 401 );

        }

I have this function to login, I am try with a Model Teacher, but always auth::attempt gave me false, but if I am try with User Model the result is true.

My Model Teacher

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use App\Student;
use App\Rating;
use App\Commentary;
use App\User;

class Teacher extends Authenticatable
{
  use Notifiable;
  use HasApiTokens;

  /**
   * 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',
  ];

  /**
   * The attributes that should be cast to native types.
   *
   * @var array
   */
  protected $casts = [
      'email_verified_at' => 'datetime',
  ];
    public function students(){
        return $this->belongsToMany('App\Student')->withTimestamps();
    }
    public function ratings(){
      return $this->hasMany('App\Rating');
    }
    public function commentaries(){
      return $this->hasMany('App\Commentary');
    }

    public function updateTeacher(Request $req){
        $validator = Validator::make($request->all(),[
        ]);
        if($validator->fails()){
          return response()->json($validator->errors());
        }
        if ($req->name)
            $this->name = $req->name;
        if ($req->email)
            $this->email = $req->email;
        if ($req->password)
            $this->password = $req->password;
        if ($req->number)
            $this->number = $req->number;
        if ($req->birth)
            $this->birth = $req->birth;
        if ($req->CPF)
            $this->CPF = $req->CPF;
        if ($req->lesson_price)
            $this->lesson_price = $req->lesson_price;
        if ($req->rent_price)
            $this->rent_price = $req->rent_price;
        if ($req->description)
            $this->description = $req->description;
        if ($req->district)
            $this->district = $req->district;
        if ($req->zone)
            $this->zone = $req->zone;
        if ($req->instruments)
            $this->instruments = $req->instruments;
        if ($req->certification)
            $this->certification = $req->certification;
        $this->save();
    }
    public function listTeachers(){
      $paginator = Teacher::paginate(10);
      return response()->json([$paginator]);
    }
    public function showTeacher($id){
      $teacher = Teacher::findOrFail($id);
      return response()->json([$teacher]);
    }

}

My Model User

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use Notifiable;
    use HasApiTokens;

    /**
     * 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',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

So i am think that Teacher have the same functions and most operations like User, thus the function auth::attempt should works with Teacher.

Upvotes: 1

Views: 223

Answers (2)

user12831743
user12831743

Reputation: 26

add teacher model to the guard in config/auth.php and then use

Auth::guard('teacher')->attempt($credentials)
'guards' => [
        'user' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'teacher' => [
            'driver' => 'session',
            'provider' => 'teachers',
        ],
    ],

 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'teachers' => [
            'driver' => 'eloquent',
            'model' => App\Teacher::class,
        ],
    ],

Upvotes: 1

awebartisan
awebartisan

Reputation: 1514

Default Laravel authentication only works with User model. It is specified in config/auth.php. If you want to use another model for authentication you can just change in auth.php.

If you want multiple models to be used for Authentication, for example, both User and Teacher , you need to look into Guards in Laravel.

Here is a link to a tutorial which explains this technique. HOW TO USE MULTIPLE AUTHENTICATION GUARDS IN A LARAVEL APP

Upvotes: 0

Related Questions