Jimmyjbk
Jimmyjbk

Reputation: 411

How do I set an incremental id length like this 000001, 000002,

I want would like to have an incremental id with a determined length like 0000001, 0000002, 0100000,... How am I suppose to set that. Any help will be welcomed.

public function up()
    {
        Schema::create('animals', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id')->index();
            $table->date('dateOfBirth');
            $table->string('gender');
            $table->string('placeOfBirth');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }

Upvotes: 0

Views: 168

Answers (1)

nakov
nakov

Reputation: 14268

I will leave the auto increment as it is, otherwise you will have to handle it manually which is painful.

You can create an accessor in your Animal model, for example:

protected $appends = ['code'];

public function getCodeAttribute()
{
    // use $this->attributes['id'] or try with $this->id
    return str_pad($this->attributes['id'], 6, "0", STR_PAD_LEFT);
}

Then to use it:

Animal::first()->code;

Upvotes: 1

Related Questions