Scenario:
I have a table in which there is a field called "Membership_ID", this is not primary key of the table and is not auto increment. Basically its a six digit UNSIGNED_ZEROFILL INT type, that needs to increment for each new record.
So what I was doing, I was getting last record in the table by created_at, and incrementing its membership_id:
$last_member = Model::orderBy('created_at', 'desc')->first();
$new_id = $last_member->membership_id++;
Strangely, a few records got duplicated membership_id. Upon inspecting I noticed the created_at time of these records with duplicated membership_id was almost identical.
Now I've changed it to:
$last_member = Model::all()->last();
$new_id = $last_member->membership_id++;
Tested it thoroughly and no duplication of Membership_ID so far.
The question is why the membership_id got duplicated in first case. In the created_at timestamp the value was not exactly similar, there was difference in seconds or in some cases the difference was of couple of minutes?