Commit 42f22330 authored by Mahmoud Aglan's avatar Mahmoud Aglan

Fix ManglesUniqueOnDelete truncation for short varchar columns

The trait was appending _del_YYMMDDHHMMSS (16 chars) without respecting
column length limits, causing varchar(20) overflow on employee_number.
Now uses shorter _d{id} suffix and truncates the original value to fit
within the declared max length per field.
Co-Authored-By: 's avatarClaude Opus 4.6 <noreply@anthropic.com>
parent 8e66a067
...@@ -21,6 +21,7 @@ class Employee extends Model ...@@ -21,6 +21,7 @@ class Employee extends Model
use BelongsToAcademy, HasUuid, SoftDeletes, ManglesUniqueOnDelete; use BelongsToAcademy, HasUuid, SoftDeletes, ManglesUniqueOnDelete;
protected array $uniqueFieldsToMangle = ['employee_number']; protected array $uniqueFieldsToMangle = ['employee_number'];
protected array $mangleMaxLengths = ['employee_number' => 20];
protected $fillable = [ protected $fillable = [
'academy_id', 'academy_id',
......
...@@ -9,11 +9,13 @@ ...@@ -9,11 +9,13 @@
public static function bootManglesUniqueOnDelete(): void public static function bootManglesUniqueOnDelete(): void
{ {
static::deleting(function ($model) { static::deleting(function ($model) {
$suffix = '_del_' . now()->format('ymdHis'); $suffix = '_d' . $model->id;
foreach ($model->getUniqueFieldsToMangle() as $field) { foreach ($model->getUniqueFieldsToMangle() as $field) {
if ($model->{$field} !== null) { if ($model->{$field} !== null) {
$model->{$field} = Str::limit($model->{$field}, 200, '') . $suffix; $maxLen = $model->getMangleMaxLength($field);
$available = $maxLen - strlen($suffix);
$model->{$field} = Str::limit($model->{$field}, max($available, 1), '') . $suffix;
} }
} }
...@@ -21,6 +23,11 @@ public static function bootManglesUniqueOnDelete(): void ...@@ -21,6 +23,11 @@ public static function bootManglesUniqueOnDelete(): void
}); });
} }
public function getMangleMaxLength(string $field): int
{
return $this->mangleMaxLengths[$field] ?? 255;
}
public function getUniqueFieldsToMangle(): array public function getUniqueFieldsToMangle(): array
{ {
return $this->uniqueFieldsToMangle ?? []; return $this->uniqueFieldsToMangle ?? [];
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment