Migration in Laravel

Tram Ho

1. Migration.

  • Migration can be understood as a version of your database at a point in time.
  • It makes it easier to share your database schema when working as a team.
  • Just run the migration and you can generate a schema just like you defined.
  • And of course you can also edit the columns in the database.

2 Create migrations.

  • To create a migration in laravel you just need to run the following command in terminal:

  • The result after running the command is that you get a migration file in the database/migrations directory
  • The --create or --table part is to indicate the name of the table and whether the migration will create a new table.
  • Each migration file is named including timestamp + tên to identify the order of migartion with each other.

3 Migration files.

  • In this file there are 2 functions, up and down .
  • Basically, function up will run when you execute php artisan migrate command and function down will run when you execute php artisan migrate:rollback command.
  • Of course, when function up is executed, it will create a table uers in your database and function down will delete that table.

4 Run migration

  • As I mentioned above, to execute the migration files, you just need to run the command:

  • And to go back to the previous state, run the command:

  • You can also specify the number of recovery steps with the --step option.

  • Laravel also gives you a way so that you don’t have to re-run migrate every time that rollback is

5. Schema

  • You can understand Schema is used to tạo, sửa, xóa,.. things related to tables in the database.

  • You can also check if the table or column exists by

  • Create column:

  • You can refer to the data types here: here

6. Foreign Key Constraints

  • To create constraints for tables, we can use the following syntax to bind for 2 tables:

Conclusion

  • Above are the basics of migration I would like to introduce to you. Hope it will help you.
  • The following section will introduce you to models in Laravel.
Share the news now

Source : Viblo