format('Y'); return DB::transaction(function () use ($organization, $prefix, $year) { $latest = Bill::withTrashed() ->where('organization_id', $organization->id) ->where('invoice_number', 'like', "{$prefix}-{$year}-%") ->orderByDesc('invoice_number') ->lockForUpdate() ->value('invoice_number'); $sequence = 1; if ($latest && preg_match('/-(\d+)$/', $latest, $matches)) { $sequence = (int) $matches[1] + 1; } return sprintf('%s-%s-%05d', $prefix, $year, $sequence); }); } }