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

MostofaL's avatar

Stancl\Tenancy: Trouble with tenant() Helper in Laravel Api Resources

I'm currently working with Laravel's Api Resources and the stancl\tenancy package using the multi-database approach.

In one of my controllers, I have the following code:

return $someTenant->run(
    function () {
        return (new someApiCollection(someApi::all()));
    }
);

The current tenant has an ID of 1, and $someTenant is a tenant with an ID of 2.

Inside the someApiResource class, when I log tenant()->id, it always shows the ID of 1:

/**
 * Transform the resource into an array.
 *
 * @return array<string, mixed>
 */
public function toArray(Request $request): array
{
    \Log::info([
        'toArray tenant()' => tenant()?->id,
    ]);
    // ...
}

Even though I've run $someTenant->run(...) at an upper level, it doesn't seem to detect the correct tenancy context.

Has anyone experienced similar behavior with the tenant() helper in the context of Api Resources and Stancl\Tenancy, and how can this be resolved?

UPDATE: when i put the same log on the constructor of the API resource, I get the correct tenant ID, but on the toArray method, I still get the incorrect ID of the tenant.

0 likes
1 reply

Please or to participate in this conversation.