ldc-showroom-bo/app/Models/Tenant.php

90 lines
2.3 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;
use Stancl\Tenancy\Contracts\Tenant as TenantContract;
use Illuminate\Support\Str;
class Tenant extends BaseTenant implements TenantContract
{
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'id',
'name',
];
/**
* Define the custom columns (that won't be stored in the data JSON column)
* by overriding the getCustomColumns() method.
*
* @see https://tenancyforlaravel.com/docs/v3/tenants
*
* @return array
*/
public static function getCustomColumns(): array
{
return [
'id',
'name',
];
}
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
// * ASSERTIONS
self::assertNameIsUnique($model->name);
// * TRANSFORMATIONS
$model->id = Str::slug($model->name);
});
static::updating(function (self $model) {
// * ASSERTIONS
self::assertNameIsUnique($model->name, $model->id);
// * TRANSFORMATIONS
$model->id = Str::slug($model->name);
});
}
// * METHODS
/**
* Asserts using validation that the name is unique
*
* @param string|null $name
* @param integer|null $id
* @return void
* @throws \Illuminate\Validation\ValidationException If name already exists.
*/
private static function assertNameIsUnique(string|null $name, ?int $id = null)
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'name', $name, $id);
ToolboxHelper::assertFieldIsUnique($table, 'id', Str::slug($name), $id);
}
// * RELATIONSHIPS
/**
* The tenants that belong to the user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
}