I have a registration_id
in format KUTWJH210117001
. Next time when the user posts the registration_id
I want to increment it to KUTWJH210117002
,
but I'm getting the output as:
KUTWJH210117001 // the first time
KUTWJH2101172 // next time it will be
KUTWJH2101173 // and so on
The Code
public function setRegistrationIdAttribute($rid)
{
$getLastRegistrationId = Driver::orderBy('id', 'desc')->first()->registration_id;
$getDateToCheck = substr($getLastRegistrationId , 6, 6);
if($getDateToCheck === date('dmy')) {
$toIncrement = substr($getLastRegistrationId, -1);
$increment = float($toIncrement++); //i'm incrementing here
$this->attributes['registration_id'] = $rid.date('dmy').$increment;
}
else
{
$this->attributes['registration_id'] = $rid.date('dmy')."001";
}
}
Thank you
Use sprintf
to format:
$this->attributes['registration_id'] = $rid.date('dmy').sprintf("%03d", $increment);
%03d
- tells that you are formatting 3 digit number. So, zero's will be padding automatically.