When creating a migrations with the command:
php artisan make:migrations create_cars
A blank file is created with two methods: up()
and down()
, and inside them are written what is to be done, example :
Is there any way to do this update of the database without deleting the data from the tables?
Creating a migrations create_cars
and within your methods:
class create_cars extends Migration
{
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('model', 100);
$table->timestamp('created_at');
});
}
public function down()
{
Schema::drop('cars');
}
}
run the command php artisan migrate
and the table with these settings and fields is created.
Next you want a change in the structure of this table which is the creation of a active
field, but that the existing data is not lost.
Create a new migrations with the command php artisan make:migrations cars_add_active
instead of Schema::create
that is to create the table, put Schema::table
that allows change in the structure of this table, which can be add fields, indexes, relationships and / or delete as well. In the example case a field is added in the table with the name of active
, type TINYINT(4)
with the default value 1 and can receive null
values.
class cars_add_active extends Migration
{
public function up()
{
Schema::table('cars', function($table){
$table->tinyInteger('active')
->default(1)
->nullable();
});
}
public function down()
{
//
}
}
Remembering that the existing data will never be deleted as explained in the example.
Here's all settings for columns and the explanation of how to proceed.
Note: Do not forget to install the package composer require
doctrine / dbal
References: