Ronnie Ronnie - 4 months ago 20
PHP Question

Adding a column to existing table

I had a migration called

projects_table
that ran

Schema::create('projects', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('user_id');
});


I needed to add a new column called
project_settings
. I assumed I could just add

$table->text('project_settings');


and run
php artisan migrate
, but I was wrong, didn't work. I then read http://laravel.com/docs/5.0/schema#adding-columns and learned I have to use
Schema::table(...);
so I changed my existing migration (projects_table) to:

Schema::table('projects', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('project_settings');
$table->integer('user_id');
});


and that still did not work. I finally got it to work by creating a new migration
ProjectsTableNewField
and simply adding

Schema::table('projects', function(Blueprint $table) {
$table->text('project_settings');
});


My question is, is that the right way to do this in laravel? Adding a column is a pretty basic task and If I have to create a migration for every database change, I think that migration folder will get long quick. What is the right way to do this?

edit: I also see it is important to have a
created_at
and
updated_at
field for migration purposes. I will add those fields as well

Answer

Yes, creating a new migration when you want to update the structure of the table is the right thing to do.

It allows you to "push" this modifications on a live server without breaking the existing database.

Their's another way of doing it, but it might no be applicable if you already stored datas in your tables :

  1. Rolling back migrations using php artisan migrate:reset
  2. Updating your existing migration file and add the new field in the field list
  3. Running migrations again : php artisan migrate

Keep in mind that this is going to delete all your existing tables, ending up in a loss of datas in case you already stored some.

Comments