'boolean', ]; } protected static function booted(): void { static::saving(function (Department $department): void { if (blank($department->code) && filled($department->name)) { $department->code = static::generateUniqueCodeFromName( $department->name, $department->id, ); } }); } public static function generateUniqueCodeFromName(string $name, ?int $ignoreId = null): string { $base = Str::upper(Str::slug($name)); $query = static::query() ->when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId)); if (! $query->clone()->where('code', $base)->exists()) { return $base; } $maxSuffix = $query->clone() ->where('code', 'like', "{$base}-%") ->pluck('code') ->map(fn (string $code): int => (int) Str::after($code, "{$base}-")) ->max(); return "{$base}-".(($maxSuffix ?? 0) + 1); } public function employees(): HasMany { return $this->hasMany(Employee::class); } public function users(): HasMany { return $this->hasMany(User::class); } }