- Introduction
- Generating migrations
- Migration Structure
- Running Migrations
- Writing Migrations
- Creating Tables
- Renaming/dropping Tables
- Creating Columns
- modifying Columns
- Dropping Columns
- Creating Indexes
- Dropping Indexes
- Foreign Key Constraints
Introduction
Migrations is like version control for your database, allowing a team to easily modify and share the application ' s Databa SE schema. Migrations is typically paired with Laravel's schema builder to easily build your application ' s database schema.
The Laravel Schema
facade provides database agnostic support for creating and manipulating tables. It shares the same expressive, fluent API across all of Laravel ' s supported database systems.
Generating migrations
To create a migration, use the make:migration
Artisan command:
php artisan make:migration create_users_table
The new migration is placed in your database/migrations
directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.
The and options may also is used to indicate the name of the table and whether the migration would be --table
--create
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=usersphp artisan make:migration create_users_table --create=users
Migration Structure
A Migration class contains-methods: up
and down
. The up
method is used to add new tables, columns, or indexes to your database, while the down
method should simply Rev Erse the operations performed by the up
method.
Within both of these methods you could use the Laravel schema Builder to expressively create and modify tables. To learn about all of the methods available on Schema
the builder and check out its documentation. For example, let's look at a sample migration that creates a flights
table:
<?phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateFlightsTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create(‘flights‘, function (Blueprint $table) { $table->increments(‘id‘); $table->string(‘name‘); $table->string(‘airline‘); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop(‘flights‘); }}
Running Migrations
To run all outstanding migrations for your application, use the migrate
Artisan command. If you are using Thehomestead Vsan, you should run the this command from within your VM:
php artisan migrate
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
Some migration operations is destructive, meaning they may cause your to lose data. In order to protect the running these commands against your production database, you'll be a prompted for Confirmatio n before these commands is executed. To force the commands-run without a prompt, use the --force
flag:
php artisan migrate --force
Rolling back migrations
To rollback the latest migration "operation", your may use the rollback
command. Note that this Rolls-the last "batch" of migrations-ran, which may include multiple migration files:
php artisan migrate:rollback
The command would roll back all of migrate:reset
your application ' s migrations:
php artisan migrate:reset
Rollback/migrate in single Command
The command would first roll migrate:refresh
to your database migrations, and then run the migrate
command. This command effectively re-creates your entire database:
php artisan migrate:refreshphp artisan migrate:refresh --seed
Writing Migrations
Creating Tables
To create a new database table with the method on the create
Schema
facade. The create
method accepts the arguments. The first is the name of the table and while the second are 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, your may use any of the schema Builder's column methods to define the table ' s columns.
Checking for Table/column existence
Easily check for the existence of a table or column using the and hasTable
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's not your default connection, use the connection
metho D:
Schema::connection(‘foo‘)->create(‘users‘, function ($table) { $table->increments(‘id‘);});
To set the storage engine for a table, set the property on the engine
schema Builder:
Schema::create(‘users‘, function ($table) { $table->engine = ‘InnoDB‘; $table->increments(‘id‘);});
Renaming/dropping Tables
To rename a existing database table, use the rename
method:
Schema::rename($from, $to);
To drop a existing table, you could use the drop
or dropIfExists
methods:
Schema::drop(‘users‘);Schema::dropIfExists(‘users‘);
Creating Columns
To update an existing table, we'll use the table
method on the Schema
facade. Like create
the method, the table
method accepts-arguments:the name of the table and a that Closure
receives a Blueprint
inst Ance we can use to add columns to the table:
Schema::table(‘users‘, function ($table) { $table->string(‘email‘);});
Available Column Types
Of course, the schema Builder contains a variety of column types that is use when building your tables:
Command
Description
$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, 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‘);
The 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 and taggable_id
STRING taggable_type
.
$table->nullableTimestamps();
Same timestamps()
as, except allows NULLs.
$table->rememberToken();
Adds as remember_token
VARCHAR (+) 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 is several other column ' modifiers ' which you could use while adding th E column. For example, the-to-make the column "nullable", the nullable
method:
Schema::table(‘users‘, function ($table) { $table->string(‘email‘)->nullable();});
Below is a list of all the available column modifiers. This list does not include the index modifiers:
Modifier
Description
->first()
Place the column ' first ' in the table (MySQL only)
->after(‘column‘)
Place the column ' after ' another column (MySQL only)
->nullable()
Allow NULL values to is inserted into the column
->default($value)
Specify a "default" value for the column
->unsigned()
Set integer
Columns toUNSIGNED
modifying columnsprerequisites
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 the column and create the SQL queries needed to make T He specified adjustments to the column.
Updating Column Attributes
change
The method allows modify an existing column to a new type, or modify the column ' s attributes. For example, you could wish to increase the size of a string column. change
to see the method in action, let's increase the size of the name
column from 50:
Schema::table(‘users‘, function ($table) { $table->string(‘name‘, 50)->change();});
We could also modify a column to be nullable:
Schema::table(‘users‘, function ($table) { $table->string(‘name‘, 50)->nullable()->change();});
Renaming Columns
To rename a column, the method on the renameColumn
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 was not currently supported.
Dropping Columns
To drop a-column, use the method on the dropColumn
Schema Builder:
Schema::table(‘users‘, function ($table) { $table->dropColumn(‘votes‘);});
You could drop multiple columns from a table by passing an array of column names to the dropColumn
method:
Schema::table(‘users‘, function ($table) { $table->dropColumn([‘votes‘, ‘avatar‘, ‘location‘]);});
Note: Before dropping columns from a SQLite database, you'll need to add the doctrine/dbal
dependency to your composer.json
file and run the c4/> command in your terminal to install the library.
Creating Indexes
The schema builder supports several types of indexes. First, let's look at the A example that specifies a column ' s values should is unique. To create the index, we can simply chain the unique
method onto the column definition:
$table->string(‘email‘)->unique();
Alternatively, you could create the index after defining the column. For example:
$table->unique(‘email‘);
Even pass an array of columns to an index method to create a compound index:
$table->index([‘account_id‘, ‘created_at‘]);
Available Index Types
Command
Description
$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.
Dropping Indexes
To drop a 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 is some examples:
Command
Description
$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.
Foreign Key Constraints
Laravel also provides support for creating foreign key constraints, which is used to force referential integrity at the D Atabase level. For example, let's define a column on the user_id
posts
table that references the id
column on a users
table:
Schema::table(‘posts‘, function ($table) { $table->integer(‘user_id‘)->unsigned(); $table->foreign(‘user_id‘)->references(‘id‘)->on(‘users‘);});
Also specify the desired action for the ' on delete ' and ' on Update ' properties of the constraint:
$table->foreign(‘user_id‘) ->references(‘id‘)->on(‘users‘) ->onDelete(‘cascade‘);
To drop a foreign key, you may use the dropForeign
method. Foreign key constraints use the same naming convention as indexes. So, we'll concatenate the table name and the columns in the constraint then suffix the name with "_foreign":
$table->dropForeign(‘posts_user_id_foreign‘);
Laravel5.1 Learning Note 17 Database 3 Data Migration