Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ofekl995's avatar

problem with sanctum api key that is based on another model (not user)

Hello! My application API keys are based on a model called organization (not users).


class organization extends Model
{
    use HasFactory,HasApiTokens;
...
}

On a request with the authorization key (using the sanctum middleware) I want to retrieve the id of the organization. I tried :

auth('sanctum')->organization()->id

which doesn't work, however if it was the user model this would work:

auth('sanctum')->user()->id

I probably need to add a method but I'm not sure where.

Thanks :)

0 likes
1 reply
tuneless's avatar

If your authenticated user belongs to an organization you could do something like:

auth('sanctum')->user()->organization->id

I would eager load organization within User-model with protected $with = ['organization'].

Additionally: You need to have a look and understanding of Laravel auth-guards and it's providers, if you want to use a different auth-guard for organizations.

https://laravel.com/docs/master/authentication#adding-custom-user-providers

Please or to participate in this conversation.