Courses

Laravel 12 Multi-Tenancy: All You Need To Know

Filter DB Records by Active Tenant

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Adding tenant_id to projects and tasks tables
- Creating FilterByTenant trait for automatic tenant assignment
- Implementing Global Scope for tenant-based filtering
- Adding BelongsToMany relationship between User and Tenant

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

Now, let's filter the records by my current team. For that, we will add tenant_id column to all the DB tables that should be "tenantable". We create a Trait, and this will be a lesson about Traits and Scopes, similar like we had in one earlier lesson.


So, let's generate two migrations to add tenant_id to projects and tasks tables.

php artisan make:migration "add tenant id to projects table"
php artisan make:migration "add tenant id to tasks table"

database/migrations/xxx_add_tenant_id_to_projects_table.php:

Schema::table('projects', function (Blueprint $table) {
$table->foreignId('tenant_id')->constrained();
});

database/migrations/xxx_add_tenant_id_to_tasks_table.php:

Schema::table('tasks', function (Blueprint $table) {
$table->foreignId('tenant_id')->constrained();
});

Now, let's create a trait, FilterByTenant.

php artisan make:trait Traits/FilterByTenant

We will use the same booted() method for...

The full lesson is only for Premium Members.
Want to access all 21 video+text lessons of this course? (1 h 21 min)

You also get:

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