mirror of https://github.com/Lukibeg/OmniBoard.git
34 lines
940 B
PHP
34 lines
940 B
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use App\Models\Tenant;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
trait BelongsToTenant
|
|
{
|
|
// O "Boot" da Trait roda automaticamente sempre que o Model é usado
|
|
protected static function bootBelongsToTenant()
|
|
{
|
|
// Se tiver usuário logado e ele tiver um tenant_id...
|
|
if (Auth::user() && Auth::user()->tenant_id) {
|
|
|
|
// Adiciona um filtro GLOBAL em todas as consultas
|
|
static::addGlobalScope('tenant', function (Builder $builder) {
|
|
$builder->where('tenant_id', Auth::user()->tenant_id);
|
|
});
|
|
|
|
// Preenche automaticamente o tenant_id ao CRIAR registros
|
|
static::creating(function ($model) {
|
|
$model->tenant_id = Auth::user()->tenant_id;
|
|
});
|
|
}
|
|
}
|
|
|
|
public function tenant()
|
|
{
|
|
return $this->belongsTo(Tenant::class);
|
|
}
|
|
}
|