Making laravel/passport tenant aware

Making laravel/passport tenant aware

There are many Laravel packages out there that help us make Laravel applications multi-tenant. Depending on the project, we chose spatie/laravel-multitenancy. The package does almost everything for you, but if you are building API endpoints, you are probably going to use laravel/passport as an authentication package to secure your API endpoints. So, combining these two packages might be a little bit tricky. Let me show you why!

Passport migration will run on the main database

Each tenant has its own users, and each user can authenticate to one tenant and should not access other tenant data. So we need our Passport migrations to run on each created tenant.  

To solve this, just run the command on your terminal

$ php artisan vendor:publish --tag=passport-migrations

so publish the migrations files and then move these files to your migrations tenant folder. This way, Passport migrations won’t run on the landlord database.

Passport migration will run automatically

Solving this is pretty easy, just add Passport::ignoreMigrations();  to your AuthServiceProvider like shown in the image below.

Passport will use the landlord database connection

By default, Laravel uses the default database connection as we call the landlord database. To force Passport use tenant connection, I’m going to create a task that will be performed when a tenant is detected and switched. But before creating this task, we should create few custom classes to extend default Passport classes. So, I’m using UsesTenantConnection trait on few Passport models as shown in the image below.

After we told Passport models to use tenant connection, we have one think left which is implementing Spatie\Multitenancy\Tasks\SwitchTenantTask interface.

Now I’m going to create a class that implements that interface and force Passport to use our custom classes.

After creating the class, don’t forget to add it to the switch_tenant_tasks array at config/multitenancy.php 

The User.php eloquent will use the landlord database connection

Depending on your situation, you can either tell the current User model to use the tenant connection by using the UsesTenantConnection trait, or create another custom model like TenantUser.php.

If you completed all those steps, you are done. Just go on and generate those tokens ! ​