ricardoarg

I am in the path of finishing my multi-tenant app. I didn't use any package... In the end it's pretty simple, the only thing I used is:

create a TenantScope

class TenantScope implements Scope
{

    public function apply(Builder $builder, Model $model)
    {        
        $id_tenant = 0;
        if (Auth::check()) {
            $id_tenant = Auth::user()->tenant_id;
        }           
        return $builder->where($model->getTable() . '.tenant_id',  '=', $id_tenant);        
    }
}

then, I have a ScopedModel base class, wich have something like this in the boot method:

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new TenantScope);

    static::creating(function ($model) {
            if (!$model->tenant_id) {
               $model->tenant_id = Auth::user()->tenant_id;         
            }
    });
    }  

and it's bassicaly done, every eloquent query on the ScopedModel will be with a "AND table.tenant_id = XXX", and every created model will have the tenant_id set.

Return to Thread...