Courses

Laravel 12 Multi-Tenancy: All You Need To Know

Multiple Tenants and Switching Between Them

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Adding current_tenant_id to users table
- Creating UI for tenant switching in navigation
- Implementing tenant switching functionality
- Updating FilterByTenant trait to use current tenant

Now, let's take care of the situation of multiple tenants per user.

We have the database structure already, with tenant_user pivot table. Now, the question is where to save the active current tenant.


Saving Current Tenant

Two choices that I would suggest:

  1. A boolean column is_active in the pivot.
  2. Saving current tenant ID in the users table.

In this lesson, we will use the second method and add the current_tenant_id column to the users table.

First, the migration.

php artisan make:migration "add current tenant id to users table"

database/migrations/xxx_add_current_tenant_id_to_users_table.php:

Schema::table('users', function (Blueprint $table) {
$table->foreignId('current_tenant_id')->nullable()->constrained('tenants');
});

app/Models/User.php:

class User extends Authenticatable
{
protected $fillable = [
'name',
'email',
'password',
'current_tenant_id',
];
 
// ...
}

Let's refresh the database so we can make sure that everything works.

php artisan migrate:fresh

Then, we need to set the active tenant when a user...

The full lesson is only for Premium Members.
Want to access all 22 lessons of this course? (88 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord