Laravel 5.3在代码中增加001到002

时间:2017-01-21 08:10:48

标签: php laravel laravel-5.3 auto-increment

我的格式为registration_id KUTWJH210117001。下次用户发布registration_id时我想将其增加到KUTWJH210117002, 但我得到的输出为:

KUTWJH210117001  // the first time  
KUTWJH2101172    // next time it will be 
KUTWJH2101173    // and so on

守则

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";
    }
}

谢谢

2 个答案:

答案 0 :(得分:2)

使用sprintf格式化:

$this->attributes['registration_id'] = $rid.date('dmy').sprintf("%03d", $increment);

%03d - 告诉您正在格式化3位数字。因此,零会自动填充。

答案 1 :(得分:2)

使用str_pad

$increment = str_pad($increment, 3, '0', STR_PAD_LEFT);