April 28, 2015

Laravel 5 Database Migrations - The Basics

Migrations are a way to "version control" a database. There are ways to "seed" data into a database, but migrations are more concerning the schema. Previously, to set up a database, a lot of manual setup needed to be done; create a table, add some columns, set their keys, etc etc. And if the database corrupted, or got blown away, or you needed to set it up on another server or share with someone else, there would probably be a bit of manual setup again, despite potential sqldumps and schema exports.

Migrations are a neat way to get around a lot of this manual setup via PHP classes. Basically, a migration is a PHP class that represents the instructions telling the database what needs to happen during setup. Laravel has an easy way to create migrations of various types; depending on what flags are used, a new PHP class with some relevant boilerplate code will be set up. For example:

php artisan make:migration create_cool_table --create="cool"

The migration file will get created and stored in the database/migrations folder as create_cool_table.php. Note the up() and down() methods within it. The former is to implement a change to the database, and the latter is to undo it via a rollback. These two methods should be exact opposites in what they accomplish.

Actually implement a migration - the up() method:
php artisan migrate

Undo the most recent migration - the down() method:
php artisan migrate:rollback

If a rollback fails, it is likely because of a missing database package. Add it:
composer require doctrine/dbal

The Laravel framework uses the migrations table in the database to keep track of which migrations were already run in the past. A migration will never be run again, unless you roll it back, as above, to make changes to it.

Caveat: If a migration has already been run on a Production server, or a friend/co-worker's machine, it is probably better to just create a fresh migration to make further changes, instead of rolling back the migrated migration, changing it, and re-migrating it. To make a change to an existing table, we are still creating a new migration, but can use different flags to set up useful boilerplate for this case:
php artisan make:migration modify_cool_table --table="cool"

As a general rule-of-thumb, it is always easier to just migrate new stuff, than to first un-migrate some stuff, then pull in the updates, then re-migrating... Keep things sequential!

No comments :

Post a Comment