Learn about Migration in Laravel.

Tram Ho

Hello, continue with the series about Laravel, today I will guide you to use Migration in Laravel .

1. General introduction

Migration in Laravel enables schema management in your database. It allows you and the team to modify and share the database schema. Companion you can manipulate on different databases without having to modify the code according to the database is in use.

2. Create Migration

To create a migration in Laravel use the command Artisan php artisan make:migration create_users_table Each named migration file includes the timestamp to determine the order of migartions together. The –table and –create options can also be used to indicate the name of the table and whether the migration will create a new table or not. These options pre-populate the migration creation command:

3. Structure a file migration

A migration class contains two methods: up and down . The up method is used to add new tables, columns, or indexes to your database, while the down method reverses the operations performed by the up method. For example, the following migration creates a flight table:

4. Run Migration

To run all migration files using the migrate command:

Move back to previous state:

You can restore a certain number of steps of migration by providing a step option for rollback, for example:

You can also rollback to the original state of migration:

Rollback and recreate your database:

If you want to rollback to the previous steps and run the migration again, you can use the following command:

The following command will delete all the tables in your database and run the migration again:

5. Schema

If we want to create a new table in our database, we can use:

If you want to check if a table or column exists or not, use the hasTable and hasColumn methods:

Rename or delete a table:

Create column:

Statements for you to type the column more easily:

SyntaxDescription
$ 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’, 0);Columns equivalent to exact data (sum of digits).
$ table-> dateTimeTz (‘created_at’, 0);The column is equivalent to DATETIME (with time zone) with precision (total digits).
$ table-> decimal (‘amount’, 8, 2);DECIMAL equivalent column with precision (total digits) and scale (decimal places).
$ table-> double (‘amount’, 8, 2);The column is equivalent to DOUBLE with precision (total digits) and ratio (decimal places).
$ table-> enum (‘level’, [‘easy’, ‘hard’]);ENUM equivalent column.
$ table-> float (‘amount’, 8, 2);FLOAT equivalent column with precision (total digits) and scale (decimal places).
$ table-> geometry (‘positions’);Column equivalent to GEOMETRY.
$ table-> geometryCollection (‘positions’);Equivalent columns GEOMETRYCOLLMENT.
$ table-> increments (‘id’);Columns automatically increment the equivalent of an equivalent column (primary key).
$ table-> integer (‘votes’);Column equivalent to INTEGER.
$ table-> ipAddress (‘visitor’);IP address equivalent column.
$ table-> json (‘options’);JSON equivalent column.
$ table-> jsonb (‘options’);JSONB equivalent column.
$ table-> lineString (‘positions’);LINE LINEING equivalent column.
$ table-> longText (‘description’);Column equivalent to LONGTEXT.
$ table-> macAddress (‘device’);MAC address column equivalent.
$ table-> mediumIncrements (‘id’);The automatic column increases similarly to the non-matching MEDIUMINT (primary key) column.
$ table-> mediumInteger (‘votes’);Column equivalent to MEDIUMINT.
$ table-> mediumText (‘description’);Column equivalent to MEDIUMTEXT.
$ table-> morphs (‘taggable’);Add the equivalent columns taggable_idBIGINT and taggable_typeVARCHAR.
$ table-> uuidMorphs (‘taggable’);Add the equivalent columns taggable_idCHAR (36) and taggable_typeVARCHAR (255) UUID.
$ table-> multiLineString (‘positions’);MULTILINESTRING equivalent column.
$ table-> multiPoint (‘positions’);Equivalent columns MULTIPOINT.
$ table-> multiPolygon (‘positions’);Equivalent columns MULTIPOLYGON.
$ table-> nullableMorphs (‘taggable’);Add nullable versions of columns.
$ table-> nullableUuidMorphs (‘taggable’);Add nullable versions of columns.
$ table-> nullableTimestamps (0);Alias ​​of the method.
$ table-> point (‘position’);SCORE equivalent columns.
$ table-> polygon (‘positions’);Columns equivalent to POLYGON.
$ table-> rememberToken ();Add a remember_token a VARCHAR equivalent (100) that cannot be empty.
$ table-> set (‘flavors’, [‘strawberry’, ‘vanilla’]);SET equivalent column.
$ table-> smallIncrements (‘id’);The equivalent column automatically increases without limitation SMALLINT (primary key).
$ table-> smallInteger (‘votes’);SMALLINT equivalent column.
$ table-> softDeletes (‘deleted_at’, 0);Add a deleted_at TIMESTAMP equivalent column that cannot be deleted for soft erase with precision (total digits).
$ table-> softDeletesTz (‘deleted_at’, 0);Add a deleted_at column equivalent to TIMESTAMP (with time zone) that cannot be deleted for soft erase with precision (total digits).
$ table-> string (‘name’, 100);Columns equivalent to VARCHAR with length.
$ table-> text (‘description’);Equivalent columns.
$ table-> time (‘sunrise’, 0);The column is equivalent to TIME with precision (total digits).
$ table-> timeTz (‘sunrise’, 0);Columns equivalent to TIME (with time zone) with precision (total digits).
$ table-> timestamp (‘added_on’, 0);Columns equivalent to TIMESTAMP with precision (total digits).
$ table-> timestampTz (‘added_on’, 0);Columns equivalent to TIMESTAMP (with time zone) with precision (total digits).
$ table-> timestamps (0);Add nullable equivalent columns created_at and updated_atTIMESTAMP with precision (total digits).
$ table-> timestampsTz (0);Add nullable equivalent columns created_at and updated_atTIMESTAMP (with time zone) with precision (total digits).
$ table-> tinyIncrements (‘id’);Automatically increment a column equivalent to TINYINT (primary key) not signed.
$ table-> tinyInteger (‘votes’);Column equivalent of TINYINT.
$ table-> unsignedBigInteger (‘votes’);The unsigned BIGINT equivalent column.
$ table-> unsignedDecimal (‘amount’, 8, 2);Equivalent UNLIMITED MINING column with precision (total digits) and scale (decimal places).
$ table-> unsignedInteger (‘votes’);Equivalent columns INTEGER INTEGER.
$ table-> unsignedMediumInteger (‘votes’);Column equivalent to MEDIUMINT.
$ table-> unsignedSmallInteger (‘votes’);Equivalent columns are NOT SMALL.
$ table-> unsignedTinyInteger (‘votes’);The unsigned TINYINT equivalent column.
$ table-> uuid (‘id’);UUID equivalent columns.
$ table-> year (‘birth_year’);Column equivalent to YEAR.

Column Modifier

ModifierDescription
-> after (‘column’)Place the column “after” another column (MySQL)
-> autoIncrement ()Setting the INTEGER column increases automatically (primary key)
-> charset (‘utf8’)Specify a character set for the column (MySQL)
-> collation (‘utf8_unicode_ci’)Specify collation for columns (MySQL / PostgreSQL / SQL Server)
-> comment (‘my comment’)Add a comment to a column (MySQL / PostgreSQL)
-> default ($ value)Specify a “default” value for the column
-> first ()Place the “first” column in the table (MySQL)
-> nullable ($ value = true)Allow (by default) NULL values ​​to be inserted into columns
-> storedAs ($ expression)Create an archived column (MySQL)
-> unsigned ()Set the INTEGER columns to UNSIGNED (MySQL)
-> useCurrent ()Set the TIMESTAMP columns to use CURRENT_TIMESTAMP as the default value
-> virtualAs ($ expression)Create a virtually created column (MySQL)
-> generatedAs ($ expression)Create an identity column with specified sequence options (PostgreSQL)
-> always ()Determines the priority of string values ​​against input for an identifier column (PostgreQuery)

Modifying Table

You can open up the terminal and install the doctrine library so you can use the useful functions in it. columns like that. 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 two migration files to run. To drop a foreign we use: $table->dropForeign('posts_user_id_foreign'); We should note the foreign naming rule <name_able> _ <foreign_key name> _foreign You can enable or disable the use of foreign key constraint in migration using the following two functions:

6. Conclusion

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

Share the news now

Source : Viblo