When you create a Migrations by command:
php artisan make:migrations create_cars
A blank file with two methods is created: up()
and down()
, and within them are written what is to be done, example:
Is there any way to do this database update without deleting data from tables?
Creating a Migrations create_cars
and within their ways:
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 is created with these settings and fields.
Soon after you want a change in the structure of this table which is the creation of a field active
, but, that existing data is not lost.
Create a new Migrations with the command php artisan make:migrations cars_add_active
and instead of Schema::create
which is to create the table, put Schema::table
which allows changes 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
, of the kind TINYINT(4)
with the default value 1 and can receive values null
.
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 existing data will never be deleted as explained in the example.
There are all the column settings and how to proceed.
Observing: don’t forget to install the package composer require
Doctrine/dbal
References:
You have the
migrations
that for example adds fields in an existing table?– novic