Schema
facade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems.make:migration
Artisan command:database/migrations
directory. Each migration file name contains a timestamp, which allows Laravel to determine the order of the migrations.--table
and --create
options may also be used to indicate the name of the table and whether or not the migration will be creating a new table. These options pre-fill the generated migration stub file with the specified table:--path
option when executing the make:migration
command. The given path should be relative to your application's base path.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.Schema
builder, check out its documentation. For example, the following migration creates a flights
table:migrate
Artisan command:--force
flag:rollback
command. This command rolls back the last 'batch' of migrations, which may include multiple migration files:step
option to the rollback
command. For example, the following command will roll back the last five migrations:migrate:reset
command will roll back all of your application's migrations:migrate:refresh
command will roll back all of your migrations and then execute the migrate
command. This command effectively re-creates your entire database:step
option to the refresh
command. For example, the following command will roll back & re-migrate the last five migrations:migrate:fresh
command will drop all tables from the database and then execute the migrate
command: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:hasTable
and hasColumn
methods:connection
method:Command | Description |
---|---|
$table->engine = 'InnoDB'; | Specify the table storage engine (MySQL). |
$table->charset = 'utf8'; | Specify a default character set for the table (MySQL). |
$table->collation = 'utf8_unicode_ci'; | Specify a default collation for the table (MySQL). |
$table->temporary(); | Create a temporary table (except SQL Server). |
rename
method:drop
or dropIfExists
methods: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 to the table:Command | Description |
---|---|
$table->id(); | Alias of $table->bigIncrements('id') . |
$table->foreignId('user_id'); | Alias of $table->unsignedBigInteger('user_id') . |
$table->bigIncrements('id'); | Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column. |
$table->bigInteger('votes'); | BIGINT equivalent column. |
$table->binary('data'); | BLOB equivalent column. |
$table->boolean('confirmed'); | BOOLEAN equivalent column. |
$table->char('name', 100); | CHAR equivalent column with a length. |
$table->date('created_at'); | DATE equivalent column. |
$table->dateTime('created_at', 0); | DATETIME equivalent column with precision (total digits). |
$table->dateTimeTz('created_at', 0); | DATETIME (with timezone) equivalent column with precision (total digits). |
$table->decimal('amount', 8, 2); | DECIMAL equivalent column with precision (total digits) and scale (decimal digits). |
$table->double('amount', 8, 2); | DOUBLE equivalent column with precision (total digits) and scale (decimal digits). |
$table->enum('level', ['easy', 'hard']); | ENUM equivalent column. |
$table->float('amount', 8, 2); | FLOAT equivalent column with a precision (total digits) and scale (decimal digits). |
$table->geometry('positions'); | GEOMETRY equivalent column. |
$table->geometryCollection('positions'); | GEOMETRYCOLLECTION equivalent column. |
$table->increments('id'); | Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column. |
$table->integer('votes'); | INTEGER equivalent column. |
$table->ipAddress('visitor'); | IP address equivalent column. |
$table->json('options'); | JSON equivalent column. |
$table->jsonb('options'); | JSONB equivalent column. |
$table->lineString('positions'); | LINESTRING equivalent column. |
$table->longText('description'); | LONGTEXT equivalent column. |
$table->macAddress('device'); | MAC address equivalent column. |
$table->mediumIncrements('id'); | Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column. |
$table->mediumInteger('votes'); | MEDIUMINT equivalent column. |
$table->mediumText('description'); | MEDIUMTEXT equivalent column. |
$table->morphs('taggable'); | Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns. |
$table->uuidMorphs('taggable'); | Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns. |
$table->multiLineString('positions'); | MULTILINESTRING equivalent column. |
$table->multiPoint('positions'); | MULTIPOINT equivalent column. |
$table->multiPolygon('positions'); | MULTIPOLYGON equivalent column. |
$table->nullableMorphs('taggable'); | Adds nullable versions of morphs() columns. |
$table->nullableUuidMorphs('taggable'); | Adds nullable versions of uuidMorphs() columns. |
$table->nullableTimestamps(0); | Alias of timestamps() method. |
$table->point('position'); | POINT equivalent column. |
$table->polygon('positions'); | POLYGON equivalent column. |
$table->rememberToken(); | Adds a nullable remember_token VARCHAR(100) equivalent column. |
$table->set('flavors', ['strawberry', 'vanilla']); | SET equivalent column. |
$table->smallIncrements('id'); | Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column. |
$table->smallInteger('votes'); | SMALLINT equivalent column. |
$table->softDeletes('deleted_at', 0); | Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes with precision (total digits). |
$table->softDeletesTz('deleted_at', 0); | Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes with precision (total digits). |
$table->string('name', 100); | VARCHAR equivalent column with a length. |
$table->text('description'); | TEXT equivalent column. |
$table->time('sunrise', 0); | TIME equivalent column with precision (total digits). |
$table->timeTz('sunrise', 0); | TIME (with timezone) equivalent column with precision (total digits). |
$table->timestamp('added_on', 0); | TIMESTAMP equivalent column with precision (total digits). |
$table->timestampTz('added_on', 0); | TIMESTAMP (with timezone) equivalent column with precision (total digits). |
$table->timestamps(0); | Adds nullable created_at and updated_at TIMESTAMP equivalent columns with precision (total digits). |
$table->timestampsTz(0); | Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns with precision (total digits). |
$table->tinyIncrements('id'); | Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column. |
$table->tinyInteger('votes'); | TINYINT equivalent column. |
$table->unsignedBigInteger('votes'); | UNSIGNED BIGINT equivalent column. |
$table->unsignedDecimal('amount', 8, 2); | UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits). |
$table->unsignedInteger('votes'); | UNSIGNED INTEGER equivalent column. |
$table->unsignedMediumInteger('votes'); | UNSIGNED MEDIUMINT equivalent column. |
$table->unsignedSmallInteger('votes'); | UNSIGNED SMALLINT equivalent column. |
$table->unsignedTinyInteger('votes'); | UNSIGNED TINYINT equivalent column. |
$table->uuid('id'); | UUID equivalent column. |
$table->year('birth_year'); | YEAR equivalent column. |
nullable
method:Modifier | Description |
---|---|
->after('column') | Place the column 'after' another column (MySQL) |
->autoIncrement() | Set INTEGER columns as auto-increment (primary key) |
->charset('utf8') | Specify a character set for the column (MySQL) |
->collation('utf8_unicode_ci') | Specify a collation for the column (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 column 'first' in the table (MySQL) |
->nullable($value = true) | Allows (by default) NULL values to be inserted into the column |
->storedAs($expression) | Create a stored generated column (MySQL) |
->unsigned() | Set INTEGER columns as UNSIGNED (MySQL) |
->useCurrent() | Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value |
->virtualAs($expression) | Create a virtual generated column (MySQL) |
->generatedAs($expression) | Create an identity column with specified sequence options (PostgreSQL) |
->always() | Defines the precedence of sequence values over input for an identity column (PostgreSQL) |
default
modifier accepts a value or an IlluminateDatabaseQueryExpression
instance. Using an Expression
instance will prevent 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: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 required adjustments:change
method allows you to modify type and attributes of existing columns. 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:renameColumn
method on the schema builder. Before renaming a column, be sure to add the doctrine/dbal
dependency to your composer.json
file:enum
is not currently supported.dropColumn
method on the schema builder. 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:dropColumn
method:Command | Description |
---|---|
$table->dropMorphs('morphable'); | Drop the morphable_id and morphable_type columns. |
$table->dropRememberToken(); | Drop the remember_token column. |
$table->dropSoftDeletes(); | Drop the deleted_at column. |
$table->dropSoftDeletesTz(); | Alias of dropSoftDeletes() method. |
$table->dropTimestamps(); | Drop the created_at and updated_at columns. |
$table->dropTimestampsTz(); | Alias of dropTimestamps() method. |
email
column and specifies that its values should be unique. To create the index, we can chain the unique
method onto the column definition:Command | Description |
---|---|
$table->primary('id'); | Adds a primary key. |
$table->primary(['id', 'parent_id']); | Adds composite keys. |
$table->unique('email'); | Adds a unique index. |
$table->index('state'); | Adds a plain index. |
$table->spatialIndex('location'); | Adds a spatial index. (except SQLite) |
utf8mb4
character set by default, which includes support for storing 'emojis' in the database. 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 this by calling the Schema::defaultStringLength
method within your AppServiceProvider
:innodb_large_prefix
option for your database. Refer to your database's documentation for instructions on how to properly enable this option.renameIndex
method. This method accepts the current index name as its first argument and the desired new name as its second argument: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. |
$table->dropSpatialIndex('geo_location_spatialindex'); | Drop a spatial index from the 'geo' table (except SQLite). |
user_id
column on the posts
table that references the id
column on a users
table:foreignId
method is an alias for unsignedBigInteger
while the constrained
method will use convention to determine the table and column name being referenced.dropForeign
method, passing the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes, based on the table name and the columns in the constraint, followed by a '_foreign' suffix:dropForeign
method. The array will be automatically converted using the constraint name convention used by Laravel's schema builder:key
option in your config/app.php
configuration file. You should use the php artisan key:generate
Online key generator for all softwares online. command to generate this key since this Artisan command will use PHP's secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure.encrypt
helper. All encrypted values are encrypted using OpenSSL and the AES-256-CBC
cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string:serialize
during encryption, which allows for encryption of objects and arrays. Thus, non-PHP clients receiving encrypted values will need to unserialize
the data. If you would like to encrypt and decrypt values without serialization, you may use the encryptString
and decryptString
methods of the Crypt
facade:decrypt
helper. If the value can not be properly decrypted, such as when the MAC is invalid, an IlluminateContractsEncryptionDecryptException
will be thrown: