Laravel Migration

Pinakamehta
2 min readMay 5, 2021

Laravel provides one powerful feature Migration. it likes version control for your database, allowing your team to define and share the application’s database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you’ve faced the problem that database migrations solve.

  • To create migration run the below command:
php artisan make:migration <migration name>

The above command will create one PHP file inside the database -> migrations folder.

Migration file has 2 methods up() and down()

Where up() will called when you run migration and down() will called when you rollback the migration. You’ve to keep in mind that you need to write code in both methods. All changes of up() must be inverse in down(). For example if you create table in up() then you’ve to drop that table and If you drop any table in up() then you’ve to create that table in down().

  • To run migration so the database can update run the below command:
php artisan migrate

After running the above command Lararave will generate one table called migrations in your database. That table has 3 columns id, migration, batch where:

  1. id — primary key
  2. migration — the name of your migration file
  3. batch — The batch number of the migrations is used to specify multiple migrations that were created while running php artisan migrate.
  • To revert the migration run the below command:
php artisan migrate:rollback

The above, command will roll back migration which batch number is highest in the migrations table. So, if you want to roll back specific migration from your list you just need to make the batch number highest. After updating, the batch number simply runs the above command.

--

--

Pinakamehta

Sr. S/W Engineer | Full Stack Web @Moweb Technologies