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:
- A boolean column
is_active
in the pivot. - 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...