Laravel migration default value

2019-06-14 22:05发布

问题:

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?

回答1:

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');



回答2:

You can simple put the default value using default(). See the example

 $table->enum('is_approved', array('0','1'))->default('0');

I have used enum here and the default value is 0.



回答3:

Mention it in the $fillable array of your model

protected $fillable = ['author', 'title', 'price',];