Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel migration default value

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('books', 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?

like image 209
nrofis Avatar asked Jun 06 '16 16:06

nrofis


People also ask

How do I change the default value in Laravel migration?

In our case we are going to do second option - create new migration. If we roll back this migration, we need to remove default value from that field using migration and this is how to do it: Schema::table('photos', function (Blueprint $table) { $table->integer('order')->default(NULL)->change(); });

What is up and down in Laravel migration?

A migration class contains two methods: up and down . The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.

Is migration necessary in Laravel?

Migrations are optional but recommended.


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

like image 144
Khan Shahrukh Avatar answered Oct 12 '22 01:10

Khan Shahrukh