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 migrateUndo the most recent migration - the
down() method:php artisan migrate:rollbackIf a rollback fails, it is likely because of a missing database package. Add it:
composer require doctrine/dbalThe 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