All individual subscriptions are 50% off this week only!

bigweld86
1 month ago
708
16
General

Laravel Passport error: createToken method doesn't exist

Posted 1 month ago by bigweld86

I'm trying to generate a token to authenticate users in my Controller the following way:

namespace App\Http\Controllers\API;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class AuthController extends Controller
{
    public function login()
    {
        if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            $user = Auth::user();
            
         
            $success['token'] = $user->createToken('myApp')->accessToken;
            dd($success['token']);
            
        }
    }

Currently, I'm just trying to print out the token. And this is my User's model:

<?php

namespace App\Models;

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

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    const USER_FIRST_NAME_FIELD        = "first_name";
    const USER_LAST_NAME_FIELD         = "last_name";
    const USER_PREFERRED_NAME_FIELD    = "preferred_name";
    const USER_EMAIL_FIELD             = "email";
    const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
    const USER_PASSWORD_FIELD          = "password";
    const USER_REMEMBER_TOKEN_FIELD    = "remember_token";
    const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
    const USER_ACTIVE_FIELD            = "active";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        self::USER_FIRST_NAME_FIELD, 
        self::USER_LAST_NAME_FIELD,
        self::USER_PREFERRED_NAME_FIELD,
        self::USER_EMAIL_FIELD,
        self::USER_PASSWORD_FIELD,
        self::USER_RECEIVE_NEWSLETTER_FIELD,
        self::USER_ACTIVE_FIELD,
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        self::USER_PASSWORD_FIELD,
        self::USER_REMEMBER_TOKEN_FIELD
    ];

    /**
     * Automatically creates password hash when password is submitted
     *
     * @param string $password
     * @return void
     */
    public function setPasswordAttribute(string $password) : void
    {
        $this->attributes['password'] = Hash::make($password);    
    }
}

As you can see I'm using HasApiTokens, Notifiable traits and nonetheless I'm getting an error from my controller saying:

Call to undefined method App\User::createToken()

Any idea why? Thanks

Please sign in or create an account to participate in this conversation.