Skip to main content

Filter DB Records by Active Tenant

Premium
3:00

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 of our courses? (30 h 41 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

KK
KWARN KHAM ✓ Link copied!

I'm trying to test this using phpunit. But auth()->user() is null in the test even with $this->actingAs() or $this->be() Please let me know how to access the user instance.

PK
Povilas Korop ✓ Link copied!

Should be working, can't really help without debugging your code on why the user doesn't stay active.

M
mfiazahmad ✓ Link copied!

Isn't $currentTenantId the first tenant of the user as a single user can belong to multiple tenants?

M
Modestas ✓ Link copied!

It is! But that was the point of this lesson. At the start of the next lesson, we move this variable to a different place to allow switching tenant ID :)

M
mfiazahmad ✓ Link copied!

Ohhh...

I think I imagined it too earlier. :)

Thanks

M
mfiazahmad ✓ Link copied!

I test my relationships on tinker. Adding this global scope, I'm unable to test them as it gives error due to user_id constraint on the models.

Is there a way to test relationships on tinker with this global scope applied or do I have to disable my trait each time I'm testing?

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.