Laravel Migration Example | Database: Migrations - Laravel | Laravel 5.5 Migration Tutorial | Database Versioning

If we manage our database manually like if you need to add a column, You directly alter the MySQL database table and add the column.
If you need to add a new table into you MySQL database you directly create a new table.
But here is the question, If you are a number of developers and working on same project how will you get to know that who changed what in your database ?
If right now you are working on second or third version of app, How will you know what was your schema when you launched first version of your application?


The answer of all these question is Migration. Laravel provides a beautiful feature of database migration.
We can manage database versioning of application. we also can track who modified what? We can manage our database through server side code.

We can create migration class for a table by artisan command like:

Here we are creating migration class for products table. Above command will create a new class in database/migrations/sometimestamp_create_products_table.php like below:

Here are 2 functions in this class up() function is used to create the schema and down function is used to drop the schema if exist.

you can edit this according to your need. For example if you wanted to to string type column and you wanted to make id as unsigned you can do it like:

Now if you will run the below migration command it insert your class into the migration table and then will create a new table 'products'.


If you have done any mistake Laravel also gives feature to rollback your migration like:

This command rolls back the last "batch" of migrations.
You also can Rollback & Migrate In Single Command like:

The migrate:refresh command will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database.

You also can define Foreign Key Constraints in migration class like if you have posts table and you wanted to foreign key constraint with users table column user_id, I mean who has created the post. You can do it like below:

Laravel 5.5 Seeding Example | Laravel Seeding | Laravel Database: Seeding

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *