@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Concerns;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Support\TenantContext;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
trait BelongsToTenant
|
||||
{
|
||||
protected static function bootBelongsToTenant(): void
|
||||
{
|
||||
static::addGlobalScope('tenant', function (Builder $builder): void {
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
|
||||
if ($tenantId !== null) {
|
||||
$builder->where($builder->qualifyColumn('tenant_id'), $tenantId);
|
||||
}
|
||||
});
|
||||
|
||||
static::creating(function (self $model): void {
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
|
||||
if ($tenantId !== null && $model->getAttribute('tenant_id') === null) {
|
||||
$model->setAttribute('tenant_id', $tenantId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user