MODULES

Multi-Tenancy


Notice: this article is about user multi-tenancy, but in April 2018 we additionally released a module for TEAMS multi-tenancy.
Check out demo video here.

What does it do?

This module allows you to restrict access to CRUD entries only to the users who actually created them.

After installing the module, you will see a checkbox for each CRUD separately, whether to use this restriction setting.


How does the result look in QuickAdminPanel code?

First, for every affected CRUD we add a field created_by_id with relationship to User model:

class Project extends Model
{
    // ...

    public function created_by()
    {
        return $this->belongsTo(User::class, 'created_by_id');
    }
}

Next, we have a special Trait for the filter by user:
app/Traits/FilterByUser.php

trait FilterByUser
{
    protected static function bootFilterByUser()
    {
        if(! app()->runningInConsole()) {
            static::creating(function ($model) {
                $model->created_by_id = Auth::getUser()->id;
            });

            $currentUser = Auth::user();
            if (!$currentUser) return;
            $canSeeAllRecordsRoleId = config('app_service.can_see_all_records_role_id');
            $modelName = class_basename(self::class);

            if ($currentUser->role_id == $canSeeAllRecordsRoleId && !is_null($canSeeAllRecordsRoleId)) {
                if (Session::get($modelName . '.filter', 'all') == 'my') {
                    Session::put($modelName . '.filter', 'my');
                    $addScope = true;
                } else {
                    Session::put($modelName . '.filter', 'all');
                    $addScope = false;
                }
            } else {
                $addScope = true;
            }

            if ($addScope) {
                static::addGlobalScope('created_by_id', function (Builder $builder) use ($currentUser) {
                    $builder->where('created_by_id', $currentUser->id);
                });
            }
        }
    }
}
The code here may look complicated, but the logic is simple - whether to add global scope or not.

Finally, we use that Trait in the model:

use App\Traits\FilterByUser;

class Project extends Model
{
    use SoftDeletes, FilterByUser;

    // ...

}

How to install/use the module?

First, go to your panel's Modules menu item, find the module in the list and click Install.

Then you will see a new checkbox for every CRUD create/edit form.


More information