0

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 :)

2 Answers2

0
<?php

namespace App;

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

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Auth\Authenticatable;

class Campaign extends Model implements AuthenticatableContract
{
    use HasApiTokens,Authenticatable;

    protected $guarded = ['id'];

    public function users()
    {

       return $this->belongsToMany(User::class)->withPivot(['percentage'])->withTimestamps();

    }
}
  • Hello Ameer, thank you! I think its a good solution and I have already tried it. It works almost the same way of what I had implemented. I still need to call auth()->user() to get the logged in "campaign". Do you now if there is another way to get logged in model? the auth()->user() approach is a little bit confusing. – Guilherme Assemany Mar 30 '20 at 14:02
  • Are you using it for Web or API – Ameer Manathat Mar 30 '20 at 14:14
  • API only. This entity will not be able to login through web. It’s just for some api routes. – Guilherme Assemany Mar 30 '20 at 14:14
0

In addition to your comment, if you like to get campaign send token in the header in the request and then search in the token table to find the related campaign

Zoran Panev
  • 23
  • 1
  • 9