After releasing our “Teams multi-tenancy” module, we’ve got a few comments and questions about some settings, the most popular was multiple teams for one user. It’s pretty hard to extend the generator for it, so we decided to build a demo-project instead.

Here’s how it looks – you can choose the team to login to, both after login moment, and also at any time from dropdown on top-right.

The code for this demo-project is available for free on GitHub. It may be useful not only to our customers, but for anyone who wants to build a multi-tenant project.

The main point of the code you need to know is a trait app/Traits/FilterByUser.php, which adds global scope for every entry for every user:

static::addGlobalScope('created_by_id', function (Builder $builder) use ($currentUser) {
    $builder->where([
        'created_by_id' => $currentUser->id,
        'created_by_team_id' => session('team_id')
    ]);
});

Also there are if-else statements which add more cases, for example Team Admin role entries are filtered only by users of their team:

static::addGlobalScope('created_by_team_id', function (Builder $builder) use ($currentUser) {
    $builder->where('created_by_team_id', $currentUser->teams->pluck('id'));
});	

Check out the full project code, or try out Teams Multi-Tenancy module in QuickAdminPanel.