Files
Wian Drs 1e80be180e
tests / ci (push) Has been cancelled
Initial commit device-management
2026-08-25 09:42:00 +07:00

36 lines
955 B
PHP

<?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);
}
}