Skip to content

Commit

Permalink
work on migration docs.
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed May 28, 2015
1 parent a53d2f6 commit 6aa8a8c
Showing 1 changed file with 104 additions and 91 deletions.
195 changes: 104 additions & 91 deletions migrations.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,48 @@
# Database: Migrations

- [Introduction](#introduction)
- [Database Migrations](#database-migrations)
- [Creating Tables](#creating-tables)
- [Creating Columns](#creating-columns)
- [Modifying Columns](#modifying-columns)
- [Creating Indexes](#creating-indexes)
- [Generating Migrations](#generating-migrations)
- [Migration Structure](#migration-structure)
- [Running Migrations](#running-migrations)
- [Rolling Back Migrations](#rolling-back-migrations)
- [Writing Migrations](#writing-migrations)
- [Creating Tables](#creating-tables)
- [Renaming / Dropping Tables](#renaming-and-dropping-tables)
- [Creating Columns](#creating-columns)
- [Modifying Columns](#modifying-columns)
- [Dropping Columns](#dropping-columns)
- [Creating Indexes](#creating-indexes)
- [Dropping Indexes](#dropping-indexes)
- [Foreign Key Constraints](#foreign-key-constraints)

<a name="introduction"></a>
## Introduction

Migrations are a type of version control for your database. They allow a team to modify the database schema and stay up to date on the current schema state. Migrations are typically paired with the [Schema Builder](/docs/{{version}}/schema) to easily manage your application's schema.
Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.

The Laravel `Schema` [facade](/docs/{{version}}/facades) provides a database agnostic way of manipulating tables. It works well with all of the databases supported by Laravel, and has a unified API across all of these systems.
The Laravel `Schema` [facade](/docs/{{version}}/facades) provides database agnostic support for creating and manipulating tables. It shares the same expressive, fluent API across all of Laravel's supported database systems.

<a name="database-migrations"></a>
## Database Migrations

### Creating Migrations
<a name="generating-migrations"></a>
## Generating Migrations

To create a migration, use the `make:migration` [Artisan command](/docs/{{version}}/artisan):

php artisan make:migration create_users_table

The new migration will be placed in your `database/migrations` folder. Each migration file name contains a timestamp which allows the framework to determine the order of the migrations.
The new migration will be placed in your `database/migrations` directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

The `--table` and `--create` options may also be used to indicate the name of the table, and whether the migration will be creating a new table. These options simply pre-fill the migration stub file that is generated by the framework with the specified table:
The `--table` and `--create` options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options simply pre-fill the generated migration stub file with the specified table:

php artisan make:migration add_votes_to_users_table --table=users

php artisan make:migration create_users_table --create=users

#### Writing Migrations
<a name="migration-structure"></a>
## Migration Structure

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

Within both of these methods you may use the `Schema` builder to expressively create and modify tables. To learn about all of the methods available on the `Schema` builder, [check out its documentation](#creating-tables). For example, let's look at a sample migration that creates a `flights` table:
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](#creating-tables). For example, let's look at a sample migration that creates a `flights` table:

<?php

Expand Down Expand Up @@ -72,13 +79,13 @@ Within both of these methods you may use the `Schema` builder to expressively cr


<a name="running-migrations"></a>
### Running Migrations
## Running Migrations

To run all outstanding migrations for your application, use the `migrate` command:
To run all outstanding migrations for your application, use the `migrate` Artisan command. If you are using the [Homestead virtual machine](/docs/{{version}}/homestead), you should run this command from within your VM:

php artisan migrate

> **Note:** If you receive a "class not found" error when running migrations, try running the `composer dump-autoload` command.
If you receive a "class not found" error when running migrations, try running the `composer dump-autoload` command and re-issuing the migrate command.

#### Forcing Migrations To Run In Production

Expand All @@ -93,9 +100,7 @@ To rollback the latest migration "operation", you may use the `rollback` command

php artisan migrate:rollback

#### Rollback All Migrations

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

php artisan migrate:reset

Expand All @@ -107,23 +112,40 @@ The `migrate:refresh` command will first roll back all of your database migratio

php artisan migrate:refresh --seed

<a name="writing-migrations"></a>
## Writing Migrations

<a name="creating-tables"></a>
## Creating Tables
### Creating Tables

To create a new database table, use the `create` method. 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 used to define the new table:
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 used to define the new table:

Schema::create('users', function ($table) {
$table->increments('id');
});

Of course, when creating the table, you may use any of the schema builder's [column methods](#creating-columns) to define the table's columns.

#### Checking For Table / Column Existence

You may easily check for the existence of a table or column using the `hasTable` and `hasColumn` methods:

if (Schema::hasTable('users')) {
//
}

if (Schema::hasColumn('users', 'email')) {
//
}

#### Connection & Storage Engine

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

Schema::connection('foo')->create('users', function ($table) {
$table->increments('id');
});

#### Storage Engine

To set the storage engine for a table, set the `engine` property on the schema builder:

Schema::create('users', function ($table) {
Expand All @@ -132,77 +154,66 @@ To set the storage engine for a table, set the `engine` property on the schema b
$table->increments('id');
});

#### Checking For Table / Column Existence

You may easily check for the existence of a table or column using the `hasTable` and `hasColumn` methods:

if (Schema::hasTable('users')) {
//
}

if (Schema::hasColumn('users', 'email')) {
//
}

<a name="renaming-and-dropping-tables"></a>
### Renaming / Dropping Tables

To rename an existing database table, the `rename` method may be used:
To rename an existing database table, use the `rename` method:

Schema::rename($from, $to);

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

Schema::drop('users');

Schema::dropIfExists('users');

<a name="creating-columns"></a>
## Creating Columns
### Creating Columns

To update an existing table, we will use the `table` method on the `Schema` facade. Like the `create` method, the `table` method accepts two arguments: the name of the table and a `Closure` that receives a `Blueprint` instance we can use to add columns to the table:

Schema::table('users', function ($table) {
$table->string('email');
});

### Available Column Types
#### Available Column Types

Of course, the schema builder contains a variety of column types that you may use when building your tables:

Command | Description
------------- | -------------
`$table->bigIncrements('id');` | Incrementing ID using a "big integer" equivalent
`$table->bigInteger('votes');` | BIGINT equivalent to the table
`$table->binary('data');` | BLOB equivalent to the table
`$table->boolean('confirmed');` | BOOLEAN equivalent to the table
`$table->char('name', 4);` | CHAR equivalent with a length
`$table->date('created_at');` | DATE equivalent to the table
`$table->dateTime('created_at');` | DATETIME equivalent to the table
`$table->decimal('amount', 5, 2);` | DECIMAL equivalent with a precision and scale
`$table->double('column', 15, 8);` | DOUBLE equivalent with precision, 15 digits in total and 8 after the decimal point
`$table->enum('choices', ['foo', 'bar']);` | ENUM equivalent to the table
`$table->float('amount');` | FLOAT equivalent to the table
`$table->increments('id');` | Incrementing ID to the table (primary key)
`$table->integer('votes');` | INTEGER equivalent to the table
`$table->json('options');` | JSON equivalent to the table
`$table->jsonb('options');` | JSONB equivalent to the table
`$table->longText('description');` | LONGTEXT equivalent to the table
`$table->mediumInteger('numbers');` | MEDIUMINT equivalent to the table
`$table->mediumText('description');` | MEDIUMTEXT equivalent to the table
`$table->morphs('taggable');` | Adds INTEGER `taggable_id` and STRING `taggable_type`
`$table->nullableTimestamps();` | Same as `timestamps()`, except allows NULLs
`$table->rememberToken();` | Adds `remember_token` as VARCHAR(100) NULL
`$table->smallInteger('votes');` | SMALLINT equivalent to the table
`$table->softDeletes();` | Adds **deleted\_at** column for soft deletes
`$table->string('email');` | VARCHAR equivalent column
`$table->string('name', 100);` | VARCHAR equivalent with a length
`$table->text('description');` | TEXT equivalent to the table
`$table->time('sunrise');` | TIME equivalent to the table
`$table->tinyInteger('numbers');` | TINYINT equivalent to the table
`$table->timestamp('added_on');` | TIMESTAMP equivalent to the table
`$table->timestamps();` | Adds **created\_at** and **updated\_at** columns

### Column Modifiers
`$table->bigIncrements('id');` | Incrementing ID using a "big integer" equivalent.
`$table->bigInteger('votes');` | BIGINT equivalent for the database.
`$table->binary('data');` | BLOB equivalent for the database.
`$table->boolean('confirmed');` | BOOLEAN equivalent for the database.
`$table->char('name', 4);` | CHAR equivalent with a length.
`$table->date('created_at');` | DATE equivalent for the database.
`$table->dateTime('created_at');` | DATETIME equivalent for the database.
`$table->decimal('amount', 5, 2);` | DECIMAL equivalent with a precision and scale.
`$table->double('column', 15, 8);` | DOUBLE equivalent with precision, 15 digits in total and 8 after the decimal point.
`$table->enum('choices', ['foo', 'bar']);` | ENUM equivalent for the database.
`$table->float('amount');` | FLOAT equivalent for the database.
`$table->increments('id');` | Incrementing ID for the database (primary key).
`$table->integer('votes');` | INTEGER equivalent for the database.
`$table->json('options');` | JSON equivalent for the database.
`$table->jsonb('options');` | JSONB equivalent for the database.
`$table->longText('description');` | LONGTEXT equivalent for the database.
`$table->mediumInteger('numbers');` | MEDIUMINT equivalent for the database.
`$table->mediumText('description');` | MEDIUMTEXT equivalent for the database.
`$table->morphs('taggable');` | Adds INTEGER `taggable_id` and STRING `taggable_type`.
`$table->nullableTimestamps();` | Same as `timestamps()`, except allows NULLs.
`$table->rememberToken();` | Adds `remember_token` as VARCHAR(100) NULL.
`$table->smallInteger('votes');` | SMALLINT equivalent for the database.
`$table->softDeletes();` | Adds `deleted_at` column for soft deletes.
`$table->string('email');` | VARCHAR equivalent column.
`$table->string('name', 100);` | VARCHAR equivalent with a length.
`$table->text('description');` | TEXT equivalent for the database.
`$table->time('sunrise');` | TIME equivalent for the database.
`$table->tinyInteger('numbers');` | TINYINT equivalent for the database.
`$table->timestamp('added_on');` | TIMESTAMP equivalent for the database.
`$table->timestamps();` | Adds `created\_at` and `updated\_at` columns.

#### Column Modifiers

In addition to the column types listed above, there are several other column "modifiers" which you may use while adding the column. For example, to make the column "nullable", you may use the `nullable` method:

Expand All @@ -221,13 +232,13 @@ Modifier | Description

<a name="changing-columns"></a>
<a name="modifying-columns"></a>
## Modifying Columns
### Modifying Columns

### Prerequisites
#### Prerequisites

Before modifying a column, be sure to add the `doctrine/dbal` dependency to your `composer.json` file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to "modify" the column to a new type.
Before modifying a column, be sure to add the `doctrine/dbal` dependency to your `composer.json` file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column.

### Updating Column Attributes
#### Updating Column Attributes

The `change` method allows you to modify an existing column to a new type, or modify the column's attributes. For example, you may wish to increase the size of a string column. To see the `change` method in action, let's increase the size of the `name` column from 25 to 50:

Expand All @@ -242,20 +253,20 @@ We could also modify a column to be nullable:
});

<a name="renaming-columns"></a>
### Renaming Columns
#### Renaming Columns

To rename a column, you may use the `renameColumn` method on the Schema builder. Before renaming a column, be sure to add the `doctrine/dbal` dependency to your `composer.json` file:

Schema::table('users', function ($table) {
$table->renameColumn('from', 'to');
});

> **Note:** Renaming columns in a table with a `enum` column is currently not supported.
> **Note:** Renaming columns in a table with a `enum` column is not currently supported.
<a name="dropping-columns"></a>
### Dropping Columns

To drop a column, you may use the `dropColumn` method on the Schema builder. Before dropping a column, be sure to add the `doctrine/dbal` dependency to your `composer.json` file:
To drop a column, use the `dropColumn` method on the Schema builder:

Schema::table('users', function ($table) {
$table->dropColumn('votes');
Expand All @@ -267,8 +278,10 @@ You may drop multiple columns from a table by passing an array of column names t
$table->dropColumn(['votes', 'avatar', 'location']);
});

> **Note:** Before dropping columns from a SQLite database, you will need to add the `doctrine/dbal` dependency to your `composer.json` file and run the `composer update` command in your terminal to install the library.
<a name="creating-indexes"></a>
## Creating Indexes
### Creating Indexes

The schema builder supports several types of indexes. First, let's look at an example that specifies a column's values should be unique. To create the index, we can simply chain the `unique` method onto the column definition:

Expand All @@ -282,30 +295,30 @@ You may even pass an array of columns to an index method to create a compound in

$table->index(['account_id', 'created_at']);

### Available Index Types
#### Available Index Types

Command | Description
------------- | -------------
`$table->primary('id');` | Adding a primary key
`$table->primary(['first', 'last']);` | Adding composite keys
`$table->unique('email');` | Adding a unique index
`$table->index('state');` | Adding a basic index
`$table->primary('id');` | Add a primary key.
`$table->primary(['first', 'last']);` | Add composite keys.
`$table->unique('email');` | Add a unique index.
`$table->index('state');` | Add a basic index.

<a name="dropping-indexes"></a>
### Dropping Indexes

To drop an index you must specify the index's name. Laravel assigns a reasonable name to the indexes by default. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:
To drop an index, you must specify the index's name. By default, Laravel automatically assigns a reasonable name to the indexes. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:

Command | Description
------------- | -------------
`$table->dropPrimary('users_id_primary');` | Dropping a primary key from the "users" table
`$table->dropUnique('users_email_unique');` | Dropping a unique index from the "users" table
`$table->dropIndex('geo_state_index');` | Dropping a basic index from the "geo" table
`$table->dropPrimary('users_id_primary');` | Drop a primary key from the "users" table.
`$table->dropUnique('users_email_unique');` | Drop a unique index from the "users" table.
`$table->dropIndex('geo_state_index');` | Drop a basic index from the "geo" table.

<a name="foreign-keys"></a>
### Foreign Key Constraints

Laravel also provides support for creating foreign key constraints to your tables, which are used to force referential integrity at the database level. For example, let's define a `user_id` column on the `posts` table that references the `id` column on a `users` table:
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 `user_id` column on the `posts` table that references the `id` column on a `users` table:

Schema::table('posts', function ($table) {
$table->integer('user_id')->unsigned();
Expand Down

0 comments on commit 6aa8a8c

Please sign in to comment.