Assemany
2 weeks ago

Laravel Sanctum (Former airlock) - How do I issue tokens for other models?

Posted 2 weeks ago by Assemany

Hello Guys,

I am trying laravel sanctum for the first time.

I want to issue tokens for an Eloquent Model called Campaign.

This is my Campaign.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Sanctum\HasApiTokens;

class Campaign extends Model
{
    use HasApiTokens;

    protected $guarded = ['id'];

    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot(['percentage'])->withTimestamps();
    }
}

As you can see, I put the HasApiTokens trait on it.

With this, I can issue a token to any campaign like that:

$campaign->createToken('my-token-name');

So far, so good. It works and is correctly stored at the database.

The problem begins when I try to use the token to make any request protected with sanctum's middleware. This is the error that shows when I do it:

Call to undefined method App\Campaign::getAuthIdentifier()

Well, I guess this getAuthIdentifier() comes from use Illuminate\Foundation\Auth\User class, which is commonly imported on the User model as Authenticatable;

I tried to create this method on my Campaign model and give it a try, that's what I've done:

public function getAuthIdentifier()
{
    return 'id';
}

When I tried to post again, it seems to work. But I think it's not correct because it's kind weird. And it gets even worse when I call auth()->user() and I am able to access the Campaign object. I know that this is a consequence of what I have done here.

Can this package issue tokens based on something that is not actually an User?

If you know how to do it correctly, I would appreciate an answer :)

It was originally posted at:

https://stackoverflow.com/questions/60876415/laravel-sanctum-former-airlock-how-do-i-issue-tokens-for-other-models

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