The issue arises because Laravel's soft deletes do not actually remove the record from the database; instead, they set the deleted_at column. If your UniqueNoGenerator checks for uniqueness using a query like:
SalesInvoice::where('invoice_no', $generatedNo)->exists()
then soft-deleted records will still be found, and the generator will think the number is taken, causing the error.
Solution:
You need to ensure that your uniqueness check ignores soft-deleted records. In Eloquent, this is done by default when using the model (unless you use withTrashed() or onlyTrashed()), but if your helper is using a raw query or not using Eloquent's default behavior, you may need to adjust it.
1. Check Your Helper
Make sure your UniqueNoGenerator uses the model's query builder, which excludes soft-deleted records by default:
SalesInvoice::where('invoice_no', $generatedNo)->exists();
If you are using withTrashed() or a custom query, remove it so soft-deleted records are not included.
2. Example Fix
If your helper uses a query like this:
$model::where($field, $number)->exists();
That is correct, as it will not include soft-deleted records.
But if you see:
$model::withTrashed()->where($field, $number)->exists();
Remove withTrashed() so soft-deleted records are not checked.
3. If You Need to Keep Numbers Unique Forever
If you want to never reuse an invoice number, even if soft-deleted, then your current logic is correct. But if you want to allow reuse after soft delete, make sure not to include soft-deleted records in your uniqueness check.
4. Example Helper Adjustment
Here’s a simplified example of how your helper should check for uniqueness:
public static function UniqueNoGenerator($model, $field, $length, $prefix)
{
do {
$number = $prefix . str_pad(mt_rand(1, 99999), $length, '0', STR_PAD_LEFT);
} while ($model::where($field, $number)->exists()); // This ignores soft-deleted records
return $number;
}
Do not use withTrashed() unless you want to include soft-deleted records.
Summary:
- Make sure your uniqueness check does not include soft-deleted records (do not use
withTrashed()). - If you want to keep numbers unique forever, include soft-deleted records.
- Adjust your helper accordingly.
If you need more specific help, please share your UniqueNoGenerator code!