Search code examples
laravellaravel-sanctumsanctum

Laravel Sanctum custom model throwing unkown column when exectuting createToken


I am using Laravel Sanctum and have customised the model (followed the config here: https://laravel.com/docs/9.x/sanctum#overriding-default-models).

Currently my model is structured like this:

id
tenant_id
name
token
abilities
last_used_at
created_at
updated_at
deleted_at (softdeletes)

When I try to create a token $user->createToken('test') I get the error:

Unknown column 'tokenable_id' in 'field list' (also 'tokenable_type') ie. it is trying to generate the token using out of the box implementation.

What would be the best way (cleanest) to get this to work. I am using it based on account based tokens rather then user based tokens.

Thanks


Solution

  • Sanctum allows you out of the box to define tokens on any model. If you have a TenantModel you can just include the trait

    class TenantModel extends Model
    {
    
    use HasApiTokens;
    ...
    

    Then you can do

    $tenant->createToken('test') 
    

    And work with the token the tenant returns you. Basically you dont need to modify the base model for your use case.

    You can also add the HasApiTokens to other Models later and there will be no issues, the same token table will be used by leveraging the morphable columns.