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

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

namespace AppHttpControllersAPI;
use IlluminateFoundationAuthAuthenticatesUsers;
use IlluminateHttpRequest;

use AppHttpControllersController;
use IlluminateSupportFacadesAuth;
use AppModelsUser;

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 AppModels;

use IlluminateNotificationsNotifiable;
//use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateSupportFacadesHash;
use LaravelPassportHasApiTokens;

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 AppUser::createToken()

Passport is installed and configured correctly.

Here’s something weird:

When registering an user (I’m using a separate controller and also using a service) a token is created successfully:

Here’s my controller:

<?php

namespace AppHttpControllersAPI;

use AppServicesUserService;
use IlluminateHttpJsonResponse;
use AppHttpControllersController;
use AppHttpRequestsRegisterUserRequest;


class UserController extends Controller 
{
    private $user;

    public function __construct(UserService $user)
    {
        $this->user = $user;
    }

    public function store(RegisterUserRequest $request) : JsonResponse
    {
        // TODO: verify message on error

        $user = $this->user->register($request->validated());
        $token = $user->createToken('MyApp')->accessToken;
        dd($token);

        return response()->json(['status' => 201, 'user_id' => $user->id]);
    }

}

Here’s my service:

<?php

namespace AppServices;

use AppModelsUser;
use AppServicesBaseServiceInterface;

class UserService implements BaseServiceInterface
{

    public function register(array $formValues) : User
    {
        // 'terms and conditions' should not be saved into the db, hence it's removed
        unset($formValues['terms_conditions']);
        return User::create($formValues);
    }

}

and here’s my model again:

<?php

namespace AppModels;

use IlluminateNotificationsNotifiable;
//use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateSupportFacadesHash;
use LaravelPassportHasApiTokens;

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
    ];

As I told you, when creating a user the token is being generated correctly.

I’d say that Auth::user() is not calling my Model directly, but I don’t know for sure that’s what is happening.

Any idea why? Thanks

Answer

Since your guard is returning the wrong User model, AppUser, you should check your auth configuration, ‘config/auth.php’. In the providers array adjust any provider, usually users, that is using the AppUser model to AppModelsUser instead.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        // 'model' => AppUser::class,
        'model' => AppModelsUser::class,
    ],
    ...
],

Leave a Reply

Your email address will not be published. Required fields are marked *