This commit is contained in:
Tito Frezer 2025-11-20 09:26:47 +01:00 committed by GitHub
commit eb0a1d94c5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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 Sanctums 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 Sanctums 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.