1
I did a basic CRUD using Eloquent.
My problem is time to create (Create). I use the code below:
public function store(Request $request)
{
$subscription = new Subscription;
// Basic Data
$subscription->custom_id = '10001';
$subscription->service_id = 1;
$subscription->imported = 1;
$subscription->review = 0;
$subscription->inserted_by = \Auth::user()->id;
$subscription->save();
}
Very simple. I can enter data normally. However, when an error occurs (for example the error Duplicate entry) and I’ll insert the next record, it skips a number (id) in the database. See images below
1) I enter a record
2) I reproduce an error
3) I enter the next record normally (10002)
Note that the next record is with id
3, and I believe it should be 2, because it did not enter the second record because I forced an error.
Why does this happen?
It is possible to avoid?
This happens to all systems or only Eloquent?
This is absolutely common. It seems that MYSQL creates a lock in the insertion process, if there is an error, the insertion is aborted, but the
id
inserted keeps increasing. Also because if you had two insertion processes at the same time, as Mysql would know "which number to reserve"?– Wallace Maxters
The error is in the field
custom_id
? by error!!! this field cannot be repeated?– novic
@Virgilionovic my problem is not the repeated field but the spaces that errors cause in auto_increment fields in sql :) The error was intentionally triggered to demonstrate the problem
– wdarking
But the error caused by the exception of your question is by the field
custom_id
and that is why the jump of theid
that fieldcustom_id
he is also a unique key?– novic
Ah yes! It’s Yuletide too, forgive not understand before
– wdarking
So @wdarking before inserting check if there is already one
custom_id
.– novic
@Virgilionovic, exactly. Validating before executing the query should be the simplest way to avoid gaps.
– wdarking
In Laravel with Eloquent one can do this in
Observer
is simple to manipulate. @wdarking Observers– novic