Home » Php » Laravel migration default value

Laravel migration default value

Posted by: admin November 30, 2017 Leave a comment

Questions:

I didn’t understand what is the effect of the default option in the migrations.

I can see that the column in the database is defined with default value, but the models are ignore it completely. Say I have a Book model that reflect the books table in the database. I have migration to create the books table:

Schema::create('bools', function (Blueprint $table) {
    $table->increments('id');
          ->string('author');
          ->string('title');
          ->decimal('price', 4, 1)->default(100);
          ->timestamps();
});

When I create a new instance of Book model I see:

$book = new Book();
var_dump($book->price); //Always 0...

The default value is ignored and the attribute is not sets correctly.
Ok, I can get it, because it is a new object and it shouldn’t get the default values from the DB. But if I tries to save model like:

$book = new Book();
$book->author = 'Test'
$book->title = 'Test'
$book->save();

It is saves 0 in the field price in the database!

So what is the point of the default option in the migrations?

By the way…
It wasn’t be better if the model see inside the migration (if exists) what are the fields types and behavior instead to define it manually in the model and the migration? And moreover, even to create a validator automatically for the model. I think that it was possible with small change of the migration structure, so why it is not like that?

Answers:

Put the default value in single quote and it will work as intended. An example of migration:

$table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->string('country');
            $table->tinyInteger('status')->default('1');
            $table->timestamps();

EDIT : in your case ->default(‘100.0’);