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 Schema
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 make:migration
Artisan command to generate a database migration. The new migration will be placed in your database/migrations
directory. Each migration filename contains a timestamp that allows Laravel to determine the order of the migrations:
php artisan make:migration create_flights_table
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 --path
option when executing the make:migration
command. The given path should be relative to your application's base path.
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 database/migrations
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 schema:dump
command:
php artisan schema:dump
// Dump the current database schema and prune all existing migrations...
php artisan schema:dump --prune
When you execute this command, Laravel will write a "schema" file to your application's database/schema
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.
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: up
and down
. The up
method is used to add new tables, columns, or indexes to your database, while the down
method should reverse the operations performed by the up
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 Schema
builder, check out its documentation. For example, the following migration creates a flights
table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFlightsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('airline');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('flights');
}
}
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 make:migration
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:
<?php
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
//
};
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 $connection
property of your migration:
/**
* The database connection that should be used by the migration.
*
* @var string
*/
protected $connection = 'pgsql';
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
}
Running Migrations
To run all of your outstanding migrations, execute the migrate
Artisan command:
php artisan migrate
If you would like to see which migrations have run thus far, you may use the migrate:status
Artisan command:
php artisan migrate:status
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 --force
flag:
php artisan migrate --force
Rolling Back Migrations
To roll back the latest migration operation, you may use the rollback
Artisan command. This command rolls back the last "batch" of migrations, which may include multiple migration files:
php artisan migrate:rollback
You may roll back a limited number of migrations by providing the step
option to the rollback
command. For example, the following command will roll back the last five migrations:
php artisan migrate:rollback --step=5
The migrate:reset
command will roll back all of your application's migrations:
php artisan migrate:reset
Roll Back & Migrate Using A Single Command
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:
php artisan migrate:refresh
// Refresh the database and run all database seeds...
php artisan migrate:refresh --seed
You may roll back and re-migrate a limited number of migrations by providing the step
option to the refresh
command. For example, the following command will roll back and re-migrate the last five migrations:
php artisan migrate:refresh --step=5
Drop All Tables & Migrate
The migrate:fresh
command will drop all tables from the database and then execute the migrate
command:
php artisan migrate:fresh
php artisan migrate:fresh --seed
The migrate:fresh
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 create
method on the Schema
facade. The create
method accepts two arguments: the first is the name of the table, while the second is a closure which receives a Blueprint
object that may be used to define the new table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->timestamps();
});
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 hasTable
and hasColumn
methods:
if (Schema::hasTable('users')) {
// The "users" table exists...
}
if (Schema::hasColumn('users', 'email')) {
// The "users" table exists and has an "email" column...
}
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 connection
method:
Schema::connection('sqlite')->create('users', function (Blueprint $table) {
$table->id();
});
In addition, a few other properties and methods may be used to define other aspects of the table's creation. The engine
property may be used to specify the table's storage engine when using MySQL:
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
// ...
});
The charset
and collation
properties may be used to specify the character set and collation for the created table when using MySQL:
Schema::create('users', function (Blueprint $table) {
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
// ...
});
The temporary
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:
Schema::create('calculations', function (Blueprint $table) {
$table->temporary();
// ...
});
Updating Tables
The table
method on the Schema
facade may be used to update existing tables. Like the create
method, the table
method accepts two arguments: the name of the table and a closure that receives a Blueprint
instance you may use to add columns or indexes to the table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('users', function (Blueprint $table) {
$table->integer('votes');
});
Renaming / Dropping Tables
To rename an existing database table, use the rename
method:
use Illuminate\Support\Facades\Schema;
Schema::rename($from, $to);
To drop an existing table, you may use the drop
or dropIfExists
methods:
Schema::drop('users');
Schema::dropIfExists('users');
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 table
method on the Schema
facade may be used to update existing tables. Like the create
method, the table
method accepts two arguments: the name of the table and a closure that receives an Illuminate\Database\Schema\Blueprint
instance you may use to add columns to the table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('users', function (Blueprint $table) {
$table->integer('votes');
});
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:
bigIncrements bigInteger binary boolean char dateTimeTz dateTime date decimal double enum float foreignId foreignIdFor foreignUuid geometryCollection geometry id increments integer ipAddress json jsonb lineString longText macAddress mediumIncrements mediumInteger mediumText morphs multiLineString multiPoint multiPolygon nullableMorphs nullableTimestamps nullableUuidMorphs point polygon rememberToken set smallIncrements smallInteger softDeletesTz softDeletes string text timeTz time timestampTz timestamp timestampsTz timestamps tinyIncrements tinyInteger tinyText unsignedBigInteger unsignedDecimal unsignedInteger unsignedMediumInteger unsignedSmallInteger unsignedTinyInteger uuidMorphs uuid year
bigIncrements()
The bigIncrements
method creates an auto-incrementing UNSIGNED BIGINT
(primary key) equivalent column:
$table->bigIncrements('id');
bigInteger()
The bigInteger
method creates a BIGINT
equivalent column:
$table->bigInteger('votes');
binary()
The binary
method creates a BLOB
equivalent column:
$table->binary('photo');
boolean()
The boolean
method creates a BOOLEAN
equivalent column:
$table->boolean('confirmed');
char()
The char
method creates a CHAR
equivalent column with of a given length:
$table->char('name', 100);
dateTimeTz()
The dateTimeTz
method creates a DATETIME
(with timezone) equivalent column with an optional precision (total digits):
$table->dateTimeTz('created_at', $precision = 0);
dateTime()
The dateTime
method creates a DATETIME
equivalent column with an optional precision (total digits):
$table->dateTime('created_at', $precision = 0);
date()
The date
method creates a DATE
equivalent column:
$table->date('created_at');
decimal()
The decimal
method creates a DECIMAL
equivalent column with the given precision (total digits) and scale (decimal digits):
$table->decimal('amount', $precision = 8, $scale = 2);
double()
The double
method creates a DOUBLE
equivalent column with the given precision (total digits) and scale (decimal digits):
$table->double('amount', 8, 2);
enum()
The enum
method creates a ENUM
equivalent column with the given valid values:
$table->enum('difficulty', ['easy', 'hard']);
float()
The float
method creates a FLOAT
equivalent column with the given precision (total digits) and scale (decimal digits):
$table->float('amount', 8, 2);
foreignId()
The foreignId
method creates an UNSIGNED BIGINT
equivalent column:
$table->foreignId('user_id');
foreignIdFor()
The foreignIdFor
method adds a {column}_id UNSIGNED BIGINT
equivalent column for a given model class:
$table->foreignIdFor(User::class);
foreignUuid()
The foreignUuid
method creates a UUID
equivalent column:
$table->foreignUuid('user_id');
geometryCollection()
The geometryCollection
method creates a GEOMETRYCOLLECTION
equivalent column:
$table->geometryCollection('positions');
geometry()
The geometry
method creates a GEOMETRY
equivalent column:
$table->geometry('positions');
id()
The id
method is an alias of the bigIncrements
method. By default, the method will create an id
column; however, you may pass a column name if you would like to assign a different name to the column:
$table->id();
increments()
The increments
method creates an auto-incrementing UNSIGNED INTEGER
equivalent column as a primary key:
$table->increments('id');
integer()
The integer
method creates an INTEGER
equivalent column:
$table->integer('votes');
ipAddress()
The ipAddress
method creates a VARCHAR
equivalent column:
$table->ipAddress('visitor');
json()
The json
method creates a JSON
equivalent column:
$table->json('options');
jsonb()
The jsonb
method creates a JSONB
equivalent column:
$table->jsonb('options');
lineString()
The lineString
method creates a LINESTRING
equivalent column:
$table->lineString('positions');
longText()
The longText
method creates a LONGTEXT
equivalent column:
$table->longText('description');
macAddress()
The macAddress
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:
$table->macAddress('device');
mediumIncrements()
The mediumIncrements
method creates an auto-incrementing UNSIGNED MEDIUMINT
equivalent column as a primary key:
$table->mediumIncrements('id');
mediumInteger()
The mediumInteger
method creates a MEDIUMINT
equivalent column:
$table->mediumInteger('votes');
mediumText()
The mediumText
method creates a MEDIUMTEXT
equivalent column:
$table->mediumText('description');
morphs()
The morphs
method is a convenience method that adds a {column}_id
UNSIGNED BIGINT
equivalent column and a {column}_type
VARCHAR
equivalent column.
This method is intended to be used when defining the columns necessary for a polymorphic Eloquent relationship. In the following example, taggable_id
and taggable_type
columns would be created:
$table->morphs('taggable');
multiLineString()
The multiLineString
method creates a MULTILINESTRING
equivalent column:
$table->multiLineString('positions');
multiPoint()
The multiPoint
method creates a MULTIPOINT
equivalent column:
$table->multiPoint('positions');
multiPolygon()
The multiPolygon
method creates a MULTIPOLYGON
equivalent column:
$table->multiPolygon('positions');
nullableTimestamps()
The nullableTimestamps
method is an alias of the timestamps method:
$table->nullableTimestamps(0);
nullableMorphs()
The method is similar to the morphs method; however, the columns that are created will be "nullable":
$table->nullableMorphs('taggable');
nullableUuidMorphs()
The method is similar to the uuidMorphs method; however, the columns that are created will be "nullable":
$table->nullableUuidMorphs('taggable');
point()
The point
method creates a POINT
equivalent column:
$table->point('position');
polygon()
The polygon
method creates a POLYGON
equivalent column:
$table->polygon('position');
rememberToken()
The rememberToken
method creates a nullable, VARCHAR(100)
equivalent column that is intended to store the current "remember me" authentication token:
$table->rememberToken();