Files
Verde-Web/app/Tenancy/HasTenant.php

34 lines
796 B
PHP

<?php
namespace App\Tenancy;
use App\Models\Tenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Apply to any model with a tenant_id column. Adds the global scope
* and auto-fills tenant_id from Tenancy::current() on creation when
* the caller didn't set one explicitly.
*
* @mixin Model
*/
trait HasTenant
{
public static function bootHasTenant(): void
{
static::addGlobalScope(new TenantScope);
static::creating(function (Model $model): void {
if (empty($model->tenant_id) && Tenancy::current()) {
$model->tenant_id = Tenancy::current()->id;
}
});
}
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
}