Home

1 minute read

How to add a new column to the database using migrations

Tony Lea

How to add a new column to the database using migrations

Using migrations in laravel 4 allows users to keep a version control of their database. If you aren't familiar with migrations I'll give you a quick rundown. A migration is a file that creates, updates, or removes tables and columns in your applications database. So, in order to add a new table using laravel 4 and migrations you can simple use the terminal and execute the following command line:

php artisan migrate:make add_details_column_to_course_table

This will simply create a new file inside of your /app/database/migrations/ folder. Once you open that file you'll see an 'up' method and a 'down' method. You can then simply change your up method to the following:

public function up()
{
	Schema::table('courses', function($table)
	{
	    $table->text('description');
	});
}

Then you can change your down method to look similar to this:

public function down()
{
	Schema::table('courses', function($table)
	{
	    $table->dropColumn('description');
	});
}

Then in your terminal command line you will simply run 'php artisan migrate', and your new column will be added to your database. Your table 'courses' will now have a new column named 'description' and your app can always be rolled back to before you added that new column.

I hope this can help someone else out. I am basically writing this post for personal documentation sake, but if it helps out someone else then that just makes the reason for writing this post that much better :)