Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Simple Multitenancy Setup

Premium
3 min read

The last thing before we start working on the Flutter mobile application is that we want multi-tenancy for our Users. In our case, we want the easiest multi-tenancy option - user_id filtering. So, let's implement the following:

  • Global scopes for Category and Transaction models
  • Refactoring of Category and Transaction controllers to create records for our user

These are small changes, but they will make our application multi-tenant. Let's start with the global scope.


Global Scopes for Category and Transaction Models

Let's start with a quick overview of our logic:

  • On our Models, we have a user_id column that relates to the User
  • We want to apply a global scope to our Models to filter records by user_id
  • This should be done automatically when we query our Models

Let's implement this in our Category model:

app/Models/Category.php

use Illuminate\Database\Eloquent\Builder;
 
// ...
 
protected static function booted(): void
{
if (auth()->check()) {
static::addGlobalScope('by_user', function (Builder $builder) {
$builder->where('user_id', auth()->id());
});
}
}

And we can do exactly the same ...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

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

Already a member? Login here

Comments & Discussion

K
kamikage ✓ Link copied!

One thing I feel this course is missing is api versioning. I feel it helps in the long run to have it start at v1 then v2 can be done later pretty easy when needed.

M
Modestas ✓ Link copied!

This can be achieved by simply pre-fixing the /api with /v1 to be fair.

But also, we specifically don't focus on all the surrounding things and just focus on the intended content. You woldn't want to hear why versioning is needed and how to implement it, if you are only looking at an example on app creation, right?

PE
Paulo Eduardo ✓ Link copied!

O caminho dos controladores esta faltando o /Api

M
Modestas ✓ Link copied!

It is not missed, since it was intentional. We are only working with API here, so there is no point of adding the prefix