php - Define property zerofill and size on field schema migration with laravel

976

How can I define property zerofill and size (2) on field schema migration with Laravel?

Schema::create('books', function (Blueprint $table) {
    $table->integer('reference')->length(2);
});

and this field with zerofill.

I would like use my seeder:

public function run()
{
    Book::create
    ([
        'reference' => 01
    ]);
}
448

Answer

Solution:

Zerofill is not a SQL standard. The shema builder of laravel provides only these ANSI SQL standards.

But you can use a workaround to define it with a raw sql statement:

create_books.php

Schema::create('books', function (Blueprint $table) {
    $table->integer('reference');
});
DB::statement('ALTER TABLE books CHANGE reference reference INT(2) UNSIGNED ZEROFILL NOT NULL');
721

Answer

Solution:

As mentioned, in order to keep your migrations portable, you'll want to use an accessor to provide that. It'll look something like this:

Book.php model

public function getReferenceAttribute($value)
{
    if($value){
        return str_pad($value, 2, '0', STR_PAD_LEFT);
    }else{
        return null;
    }
}

People are also looking for solutions to the problem: php - Modulus inside loop

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.