Doctrine Query Builder where in the array case

Database: Migrations

Introduction

Migrations are like 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.

The Laravel facade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems. Typically, migrations will use this facade to create and modify database tables and columns.

Generating migrations

You may use the Artisan command to generate a database migration. The new migration will be placed in your directory. Each migration filename contains a timestamp that allows Laravel to determine the order of the migrations:

Laravel will use the name of the migration to attempt to guess the name of the table and whether or not the migration will be creating a new table. If Laravel is able to determine the table name from the migration name, Laravel will pre-fill the generated migration file with the specified table. Otherwise, you may simply specify the table in the migration file manually.

If you would like to specify a custom path for the generated migration, you may use the option when executing the command. The given path should be relative to your application's base path.

{tip} Migration stubs may be customized using stub publishing.

Squashing migrations

As you build your application, you may accumulate more and more migrations over time. This can lead to your directory becoming bloated with potentially hundreds of migrations. If you would like, you may "squash" your migrations into a single SQL file. To get started, execute the command:

When you execute this command, Laravel will write a "schema" file to your application's directory. Now, when you attempt to migrate your database and no other migrations have been executed, Laravel will execute the schema file's SQL statements first. After executing the schema file's statements, Laravel will execute any remaining migrations that were not part of the schema dump.

You should commit your database schema file to source control so that other new developers on your team may quickly create your application's initial database structure.

{note} Migration squashing is only available for the MySQL, PostgreSQL, and SQLite databases and utilizes the database's command-line client. Schema dumps may not be restored to in-memory SQLite databases.

Migration Structure

A migration class contains two methods: and. The method is used to add new tables, columns, or indexes to your database, while the method should reverse the operations performed by the method.

Within both of these methods, you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the builder, check out its documentation. For example, the following migration creates a table:

Anonymous migrations

As you may have noticed in the example above, Laravel will automatically assign a class name to all of the migrations that you generate using the command. However, if you wish, you may return an anonymous class from your migration file. This is primarily useful if your application accumulates many migrations and two of them have a class name collision:

Setting The Migration Connection

If your migration will be interacting with a database connection other than your application's default database connection, you should set the property of your migration:

Running migrations

To run all of your outstanding migrations, execute the Artisan command:

If you would like to see which migrations have run thus far, you may use the Artisan command:

Forcing Migrations To Run In Production

Some migration operations are destructive, which means they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the flag:

Rolling back migrations

To roll back the latest migration operation, you may use the Artisan command. This command rolls back the last "batch" of migrations, which may include multiple migration files:

You may roll back a limited number of migrations by providing the option to the command. For example, the following command will roll back the last five migrations:

The command will roll back all of your application's migrations:

Roll Back & Migrate Using A Single Command

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

You may roll back and re-migrate a limited number of migrations by providing the option to the command. For example, the following command will roll back and re-migrate the last five migrations:

Drop All Tables & Migrate

The command will drop all tables from the database and then execute the command:

{note} The command will drop all database tables regardless of their prefix. This command should be used with caution when developing on a database that is shared with other applications.

Tables

Creating Tables

To create a new database table, use the method on the facade. The method accepts two arguments: the first is the name of the table, while the second is a closure which receives a object that may be used to define the new table:

When creating the table, you may use any of the schema builder's column methods to define the table's columns.

Checking For Table / Column Existence

You may check for the existence of a table or column using the and methods:

Database Connection & Table Options

If you want to perform a schema operation on a database connection that is not your application's default connection, use the method:

In addition, a few other properties and methods may be used to define other aspects of the table's creation. The property may be used to specify the table's storage engine when using MySQL:

The and properties may be used to specify the character set and collation for the created table when using MySQL:

The method may be used to indicate that the table should be "temporary". Temporary tables are only visible to the current connection's database session and are dropped automatically when the connection is closed:

Updating tables

The method on the facade may be used to update existing tables. Like the method, the method accepts two arguments: the name of the table and a closure that receives a instance you may use to add columns or indexes to the table:

Renaming / dropping tables

To rename an existing database table, use the method:

To drop an existing table, you may use the or methods:

Renaming Tables With Foreign Keys

Before renaming a table, you should verify that any foreign key constraints on the table have an explicit name in your migration files instead of letting Laravel assign a convention based name. Otherwise, the foreign key constraint name will refer to the old table name.

Columns

Creating Columns

The method on the facade may be used to update existing tables. Like the method, the method accepts two arguments: the name of the table and a closure that receives an instance you may use to add columns to the table:

Available column types

The schema builder blueprint offers a variety of methods that correspond to the different types of columns you can add to your database tables. Each of the available methods are listed in the table below:

The method creates an auto-incrementing (primary key) equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column with a given length:

The method creates a (with timezone) equivalent column with an optional precision (total digits):

The method creates an equivalent column with an optional precision (total digits):

The method creates an equivalent column:

The method creates an equivalent column with the given precision (total digits) and scale (decimal digits):

The method creates an equivalent column with the given precision (total digits) and scale (decimal digits):

The method creates an equivalent column with the given valid values:

The method creates an equivalent column with the given precision (total digits) and scale (decimal digits):

The method is an alias of the method:

The method creates an equivalent column:

The method creates an equivalent column:

The method is an alias of the method. By default, the method will create an column; however, you may pass a column name if you would like to assign a different name to the column:

The method creates an auto-incrementing equivalent column as a primary key:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates a column that is intended to hold a MAC address. Some database systems, such as PostgreSQL, have a dedicated column type for this type of data. Other database systems will use a string equivalent column:

The method creates an auto-incrementing equivalent column as a primary key:

The method creates an equivalent column:

The method creates an equivalent column:

The method is a convenience method that adds an equivalent column and an equivalent column.

This method is intended to be used when defining the columns necessary for a polymorphic eloquent relationship. In the following example, and columns would be created:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method is similar to the timestamps method; however, the column that is created will be "nullable":

The method is similar to the morphs method; however, the columns that are created will be "nullable":

The method is similar to the uuidMorphs method; however, the columns that are created will be "nullable":

The method creates an equivalent column:

The method creates an equivalent column:

The method creates a nullable, equivalent column that is intended to store the current "remember me" authentication token:

The method creates an equivalent column with the given list of valid values:

The method creates an auto-incrementing equivalent column as a primary key:

The method creates an equivalent column:

The method adds a nullable (with timezone) equivalent column with an optional precision (total digits). This column is intended to store the timestamp needed for Eloquent's "soft delete" functionality:

The method adds a nullable equivalent column with an optional precision (total digits). This column is intended to store the timestamp needed for Eloquent's "soft delete" functionality:

The method creates an equivalent column of the given length:

The method creates an equivalent column:

The method creates a (with timezone) equivalent column with an optional precision (total digits):

The method creates an equivalent column with an optional precision (total digits):

The method creates a (with timezone) equivalent column with an optional precision (total digits):

The method creates an equivalent column with an optional precision (total digits):

The method creates and (with timezone) equivalent columns with an optional precision (total digits):

The method creates and equivalent columns with an optional precision (total digits):

The method creates an auto-incrementing equivalent column as a primary key:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column with an optional precision (total digits) and scale (decimal digits):

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method creates an equivalent column:

The method is a convenience method that adds an equivalent column and an equivalent column.

This method is intended to be used when defining the columns necessary for a polymorphic eloquent relationship that use UUID identifiers. In the following example, and columns would be created:

The method creates an equivalent column:

The method creates an equivalent column:

Column modifiers

In addition to the column types listed above, there are several column "modifiers" you may use when adding a column to a database table. For example, to make the column "nullable", you may use the method:

The following table contains all of the available column modifiers. This list does not include index modifiers:

ModifierDescription
Place the column "after" another column (MySQL).
Set INTEGER columns as auto-incrementing (primary key).
Specify a character set for the column (MySQL).
Specify a collation for the column (MySQL / PostgreSQL / SQL Server).
Add a comment to a column (MySQL / PostgreSQL).
Specify a "default" value for the column.
Place the column "first" in the table (MySQL).
Set the starting value of an auto-incrementing field (MySQL / PostgreSQL).
Allow NULL values ​​to be inserted into the column.
Create a stored generated column (MySQL).
Set INTEGER columns as UNSIGNED (MySQL).
Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value.
Set TIMESTAMP columns to use CURRENT_TIMESTAMP when a record is updated.
Create a virtual generated column (MySQL).
Create an identity column with specified sequence options (PostgreSQL).
Defines the precedence of sequence values ​​over input for an identity column (PostgreSQL).

Default expressions

The modifier accepts a value or an instance. Using an instance will prevent Laravel from wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values ​​to JSON columns:

{note} Support for default expressions depends on your database driver, database version, and the field type. Please refer to your database's documentation.

Column order

When using the MySQL database, the method may be used to add columns after an existing column in the schema:

Modifying Columns

Prerequisites

Before modifying a column, you must install the package using the Composer package manager. The Doctrine DBAL library is used to determine the current state of the column and to create the SQL queries needed to make the requested changes to your column:

If you plan to modify columns created using the method, you must also add the following configuration to your application's configuration file:

{note} If your application is using Microsoft SQL Server, please ensure that you install.

Updating column attributes

The method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a column. To see the method in action, let's increase the size of the column from 25 to 50. To accomplish this, we simply define the new state of the column and then call the method:

We could also modify a column to be nullable:

{note} The following column types can be modified:,,,,,,,,,,,,,,,,,,, and. To modify a column type a Doctrine type must be registered.

Renaming columns

To rename a column, you may use the method provided by the schema builder blueprint. Before renaming a column, ensure that you have installed the library via the Composer package manager:

{note} Renaming an column is not currently supported.

Dropping columns

To drop a column, you may use the method on the schema builder blueprint. If your application is utilizing an SQLite database, you must install the package via the Composer package manager before the method may be used:

You may drop multiple columns from a table by passing an array of column names to the method:

{note} Dropping or modifying multiple columns within a single migration while using an SQLite database is not supported.

Available command aliases

Laravel provides several convenient methods related to dropping common types of columns. Each of these methods is described in the table below:

CommandDescription
Drop the and columns.
Drop the column.
Drop the column.
Alias ​​of method.
Drop the and columns.
Alias ​​of method.

Indexes

Creating Indexes

The Laravel schema builder supports several types of indexes. The following example creates a new column and specifies that its values ​​should be unique. To create the index, we can chain the method onto the column definition:

Alternatively, you may create the index after defining the column. To do so, you should call the method on the schema builder blueprint. This method accepts the name of the column that should receive a unique index:

You may even pass an array of columns to an index method to create a compound (or composite) index:

When creating an index, Laravel will automatically generate an index name based on the table, column names, and the index type, but you may pass a second argument to the method to specify the index name yourself:

Available index types

Laravel's schema builder blueprint class provides methods for creating each type of index supported by Laravel. Each index method accepts an optional second argument to specify the name of the index. If omitted, the name will be derived from the names of the table and column (s) used for the index, as well as the index type. Each of the available index methods is described in the table below:

CommandDescription
Adds a primary key.
Adds composite keys.
Adds a unique index.
Adds an index.
Adds a spatial index (except SQLite).

Index Lengths & MySQL / MariaDB

By default, Laravel uses the character set. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure the default string length by calling the method within the method of your class:

Alternatively, you may enable the option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

Renaming Indexes

To rename an index, you may use the method provided by the schema builder blueprint. This method accepts the current index name as its first argument and the desired name as its second argument:

Dropping indexes

To drop an index, you must specify the index's name. By default, Laravel automatically assigns an index name based on the table name, the name of the indexed column, and the index type. Here are some examples:

CommandDescription
Drop a primary key from the "users" table.
Drop a unique index from the "users" table.
Drop a basic index from the "geo" table.
Drop a spatial index from the "geo" table (except SQLite).

If you pass an array of columns into a method that drops indexes, the conventional index name will be generated based on the table name, columns, and index type:

Foreign key constraints

Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a column on the table that references the column on a table:

Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. The example above can be rewritten like so:

The method is an alias for while the method will use conventions to determine the table and column name being referenced. If your table name does not match Laravel's conventions, you may specify the table name by passing it as an argument to the method:

You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

Any additional column modifiers must be called before the method:

Dropping Foreign Keys

To drop a foreign key, you may use the method, passing the name of the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes. In other words, the foreign key constraint name is based on the name of the table and the columns in the constraint, followed by a "_foreign" suffix:

Alternatively, you may pass an array containing the column name that holds the foreign key to the method. The array will be converted to a foreign key constraint name using Laravel's constraint naming conventions:

Toggling Foreign Key Constraints

You may enable or disable foreign key constraints within your migrations by using the following methods:

{note} SQLite disables foreign key constraints by default. When using SQLite, make sure to enable foreign key support in your database configuration before attempting to create them in your migrations. In addition, SQLite only supports foreign keys upon creation of the table and not when tables are altered.