Skip to content
Advertisement

Failed Login with Tymon JWT Auth Laravel 8

When I try to get token with login function I get this error

TypeError: Argument 1 passed to TymonJWTAuthJWTGuard::login() must be an instance of TymonJWTAuthContractsJWTSubject, instance of AppModelsUser given, called in …vendortymonjwt-authsrcJWTGuard.php on line 127 in file …vendortymonjwt-authsrcJWTGuard.php on line 140

Here my login function:

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        if (!$token = auth()->attempt($validator->validated())) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

Here my User model:

<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;
use TymonJWTAuthContractsJWTSubject;


class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

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

    
}

How to solve my issue?

Advertisement

Answer

You must implement TymonJWTAuthContractsJWTSubject contract to your User model.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement