36 lines
910 B
PHP
36 lines
910 B
PHP
<?php
|
|
|
|
namespace App\Observers;
|
|
|
|
use App\Models\Employee;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class EmployeeObserver
|
|
{
|
|
public function creating(Employee $employee): void
|
|
{
|
|
if (filled($employee->employee_code)) {
|
|
return;
|
|
}
|
|
|
|
$year = now()->format('Y');
|
|
$prefix = "EMP-{$year}-";
|
|
|
|
$employee->employee_code = DB::transaction(function () use ($prefix): string {
|
|
$latestCode = Employee::withTrashed()
|
|
->where('employee_code', 'like', $prefix.'%')
|
|
->lockForUpdate()
|
|
->orderByDesc('employee_code')
|
|
->value('employee_code');
|
|
|
|
$sequence = 1;
|
|
|
|
if ($latestCode !== null) {
|
|
$sequence = (int) substr($latestCode, strlen($prefix)) + 1;
|
|
}
|
|
|
|
return $prefix.str_pad((string) $sequence, 4, '0', STR_PAD_LEFT);
|
|
});
|
|
}
|
|
}
|