Learn about Migration in Laravel

Tram Ho

Hello brother. Introduction to the Laravel series and the interesting things about it , today I will introduce you how to use Migrations in Laravel.

1. General introduction

Migration is like a version management system like Git but for your database. Migration allows you to define tables in the database, define the contents of the tables as well as update and change those tables completely by PHP. Also, manipulations with this database can be used on different types of databases such as MySQL, SQL Server, Postgres, … without having to edit the code according to the database used.
Prerequisites to run the migration successfully:

  • Must have a database connection.
  • The migrations you want to use must be in the App database migrations folder

2. Try to create a Migration test

To create a migration we have 2 ways to create, one is to go to the database / migrations to create a new file in it. But this way people often do not use much, people often use the way to manipulate the command line.
To create a migration, we will use the make: migration File migration command, which will be placed in the database / migrations directory

Each migration file is named including timestamp to determine the migartion order together. For example, to create a new posts table in CSDl we will use the following command: php artisan make:migration create_table_posts_table --create=posts.

When we press enter, immediately the file will be created in the database / migration folder and the content of the file will be as follows:

To add fields to the posts table in the database we will add the function up() in the file migration.

Then to create the table in the database, we will use the command: php artisan migrate
Now a problem arises when we quickly migrate and remember that we lack the status field of the posts table. Don't worry, we just need to create a new migration file with the parameter in the command is –table = posts. The command will be:
php artisan make:migration add_attribute_status_into_posts_table --table=posts

And then we migrate again as usual
If you run the php artisan migrate command and get a "class not found" error then try executing this command: composer dump-autoload first and then migrate as usual.

Attention.

I almost forgot when anyone noticed that when we installed a brand new project, there were already 2 file migration files in the database / migration directory and when we migrated for the first time, when we looked in our database, a migrations table would appear.

You pay attention to the column batch , this column we can understand the number of migrations created, for example, the migrations table above 3 migrations with id 1 2 3 has been migrated at the first time, migration with id = 4 migrated at 2nd,…
Did you notice that the name of the migration, it shows the time I created the migration and the 6 radom numbers after the time specified in the migration file shows which migration file was created first, which file migration was created later.

Another thing is why a new project has 2 files available for migration in database / migrations, I guess the writer of this Laravel framework predicts that a system will always have login / logout / regisster functionality. created 2 migrations for me already =)))

One more thing is that when we want to migrate only one migration file, we will use the command: php artisan migrate --path=...
For example, if we only want to run the migration file 2014_10_12_000000_create_users_table, we can create a new folder database / migrations / users containing the above migration file and run the command php artisan migrate –path = database / migrations / users

3.Rollback / Migrate in a command.

The php artisan migrate:refresh command will first rollback the entire migration of the program, and execute the migrate statement. That is, performing the down () function and then performing the up () function in the file migration.
The command will perform a refactoring of the entire database:
php artisan migrate:refresh
php artisan migrate:refresh --seed
The --seed parameter is to run all the Seeders we will learn in the next article.
If you want to perform the function down () with the number of batches you want to rollback, then use the command: php artisan migrate:rollback -step=n

4.Schema

We will now have a closer look at how the Schema facade operates. In the migration file to use Schema , we will use IlluminateSupportFacadesSchema .
If we want to create a new table in our database, we can use it

If you want to check if a table or column exists, we use it

If you want to rename the table from post to posts then we use it

When we want to delete the table, we can use Schema::drop()

Column types

Command description
$table->bigIncrements('id'); Increase the ID (primary key) used as "UNSIGNED BIG INTEGER".
$table->bigInteger('votes'); Equivalent to BIGINT.
$table->binary('data'); Equivalent to BLOB.
$table->boolean('confirmed'); Equivalent to BOOLEAN.
$table->char('name', 4); Equivalent to CHAR with a given length.
$table->date('created_at'); Equivalent to DATE.
$table->dateTime('created_at'); Equivalent to DATETIME.
$table->dateTimeTz('created_at'); Equivalent to DATETIME (with timezone).
$table->decimal('amount', 5, 2); Equivalent to DECIMAL with policy degrees and fractions.
$table->double('column', 15, 8); Equivalent to DOUBLE with precision, 15 digits and 8 characters after a comma.
$table->enum('choices', ['foo', 'bar']); Equivalent to ENUM.
$table->float('amount', 8, 2); Equivalent to FLOAT, 8 digits and 2 digits after the comma.
$table->increments('id'); Increase the ID (primary key) used as "UNSIGNED INTEGER".
$table->integer('votes'); equivalent to INTEGER
$table->ipAddress('visitor') equivalent to IP address
$table->json('options') equivalent to JSON
$table->jsonb('options') equivalent to JSONB
$table->longText('description') equivalent to LONGTEXT
$table->macAddress('device') equivalent to MAC address
$table->mediumInteger('numbers') equivalent to MEDIUMINT
$table->mediumText('description') equivalent to MEDIUMTEXT
$table->morphs('taggable') add INTEGER taggable_id and STRING taggable_type
$table->nullableTimestamps() same with timestamps (), except that it allows NULLs to be used
$table->rememberToken() Add remember_token as VARCHAR (100) NULL
$table->smallInteger('votes') equivalent to SMALLINT
$table->softDeletes() Add deleted_at column to soft deletes
$table->string('email') equivalent to VARCHAR
$table->string('name', 100) equivalent to VARCHAR of length
$table->text('description') equivalent to TEXT
$table->time('sunrise') equivalent to TIME
$table->timeTz('sunrise') equivalent to TIME (with timezone)
$table->tinyInteger('numbers') equivalent to TINYINT
$table->timestamp('added_on') equivalent to TIMESTAMP
$table->timestampTz('added_on') equivalent to TIMESTAMP
$table->timestamps() Add two created_at and updated_at columns
$table->uuid('id') equivalent to UUID

Column Modifier

Sometimes we may want the column in the table to be null or not null , so Laravel supports modifiers
For example, we want to leave the address column in the users table allowed to be null

And there are many more modifiers you can refer to the table below

Modifier description
after ('column') Place the "after" column another column (MySQL Only)
comment ('my comment') Add a comment to the column
default ($ value) Set the "default" value in the column
first () Place the column "first" in the table (MySQL Only)
nullable() Allow NULL data to be inserted into columns
storedAs ($ expression) Create a stored column (MySQL Only)
unsigned () Set the integer column to UNSIGNED
virtualAs ($ expression) Create a virtual column (MySQL Only)

Modifying Columns

You can open up the terminal and install the doctrine library so you can use the useful functions in it. composer require doctrine/dbal
We often make mistakes when we migrate tables and then remember we don't want to name columns like that anymore. To solve that problem, the doctrine library has a handle function.

Or another problem is that I want to limit the data type value of a column

Foreign Key Constraints

Sometimes when we want to create constraints for tables, we can use the following syntax to force ties to two tables:

Note that if you cannot run, you can split into 2 migration files to run.
To drop a foreign we use: $table->dropForeign('posts_user_id_foreign');
We should pay attention to the rule of naming foreign <tên_table>_<tên_khóa_ngoại>_foreign
You can enable or disable foreign key constraint in migration using the following two functions:

5. Conclusion

I have introduced the most basic things about Migration in Laravel, see the following article. If you have any questions, please leave a comment below!

Share the news now

Source : Techtalk