From 250f0143efc6b2476d1292fcad2cc1046f82b679 Mon Sep 17 00:00:00 2001 From: Tito Frezer Date: Mon, 20 Oct 2025 11:44:51 +0300 Subject: [PATCH] Document Sanctum API token integration for Laravel 12 Added instructions for integrating Laravel Sanctum's API token authentication with Tenancy for Laravel in Laravel 12, including middleware configuration. --- source/docs/v3/integrations/sanctum.blade.md | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/source/docs/v3/integrations/sanctum.blade.md b/source/docs/v3/integrations/sanctum.blade.md index 7153b11..47f2d54 100644 --- a/source/docs/v3/integrations/sanctum.blade.md +++ b/source/docs/v3/integrations/sanctum.blade.md @@ -38,3 +38,37 @@ To use the `sanctum.csrf-cookie` route in both the central and the tenant apps: 3. Remove `Sanctum::ignoreMigrations()` from your `AuthServiceProvider`'s `register()` method 4. Remove `'routes' => false` from the `sanctum.php` config 5. Add the `'universal'` middleware to the `sanctum.csrf-cookie` route in your `routes/tenant.php` + +### Sanctum API Token Integration with Laravel 12 {#sanctum-api-token-integration-laravel-12} + +When integrating **Laravel Sanctum’s API token authentication** with **Tenancy for Laravel** in **Laravel 12**, you may encounter an issue where: + +```php +$request->user(); // returns null +``` +even though you have correctly applied the auth:sanctum middleware. + +This happens because, in Laravel 12, middleware registration is handled via the new bootstrap/app.php file, and the tenancy initialization middleware must run before Sanctum’s authentication middleware in the API middleware stack. + +To resolve this, update your bootstrap/app.php as follows: +```php +use App\Http\Middleware\InitializeTenancyBySubDomain; +use Illuminate\Foundation\Configuration\Middleware; + +return Application::configure(basePath: dirname(__DIR__)) + ->withMiddleware(function (Middleware $middleware): void { + $middleware->web([]); + + // 👇 Important: Prepend tenancy middleware before Sanctum runs + $middleware->api(prepend: [ + InitializeTenancyBySubDomain::class, + ]); + }) + ->create(); +``` + +With this change, the tenancy context initializes before Sanctum authenticates the user, allowing $request->user() to resolve correctly to the authenticated tenant user. + +Note: In earlier Laravel versions (≤11), middleware order was managed in app/Http/Kernel.php. +Since Laravel 12 replaces that with bootstrap/app.php, explicit ordering via withMiddleware() is now required. +