#Undefined method 'createToken' in AuthController.php

5 messages · Page 1 of 1 (latest)

worn pine
#

I'm a front end dev and new to Laravel. I'm building a login page but I'm getting error in AuthController.php that says: Undefined method 'createToken'.

Github copilot is no help here. Not even Deepseek and chatGPT are able to help.

This is my code in AuthController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($request->only('email', 'password'))) {
            $user = Auth::user();
            return response()->json([
                'user' => Auth::user(),
                'token' => Auth::user()->createToken('auth_token')->plainTextToken,
            ]);
        }

        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logged out']);
    }
}

This is my User model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

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

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

flat quiver
#

Might be worth sharing the exact error you're seeing

#

Including the stack trace

worn pine
#

Here you go

flat quiver
#

So that's just your IDE complaining, as the method might not exist, it doesn't understand it's an instance of the User model. It's not actually an error if it works. Your logs don't contain that error.
To solve it you might want to use the ide-helper package, or the Laravel plugin might also tell your IDE what's going on