banner



How To Set Default Value In Laravel Migration

Database: Migrations

  • Introduction
  • Generating Migrations
    • Squashing Migrations
  • Migration Structure
  • Running Migrations
    • Rolling Back Migrations
  • Tables
    • Creating Tables
    • Updating Tables
    • Renaming / Dropping Tables
  • Columns
    • Creating Columns
    • Available Column Types
    • Column Modifiers
    • Modifying Columns
    • Dropping Columns
  • Indexes
    • Creating Indexes
    • Renaming Indexes
    • Dropping Indexes
    • Strange Cardinal Constraints
  • Events

Introduction

Migrations are similar version control for your database, allowing your team to ascertain and share the application'southward database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema subsequently pulling in your changes from source command, you've faced the trouble 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 utilise this facade to create and modify database tables and columns.

Generating Migrations

You may apply the make:migration Artisan control 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 brand:migration create_flights_table

Laravel volition use the proper noun of the migration to attempt to guess the proper noun of the table and whether or not the migration will exist creating a new table. If Laravel is able to determine the table proper name from the migration proper noun, Laravel will pre-fill up the generated migration file with the specified tabular array. Otherwise, y'all may simply specify the table in the migration file manually.

If you would similar to specify a custom path for the generated migration, you may utilise the --path pick when executing the make:migration control. The given path should exist 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 accrue more than and more than migrations over time. This can pb 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 y'all execute this command, Laravel will write a "schema" file to your awarding'due south database/schema directory. Now, when you endeavour to drift your database and no other migrations have been executed, Laravel will execute the schema file'south SQL statements beginning. Afterwards executing the schema file's statements, Laravel will execute any remaining migrations that were not function of the schema dump.

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

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

Migration Structure

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

Within both of these methods, you may apply the Laravel schema architect 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 post-obit migration creates a flights tabular array:

                                        

<?php

utilize Illuminate\Database\Migrations\ Migration ;

use Illuminate\Database\Schema\ Blueprint ;

use Illuminate\Support\Facades\ Schema ;

return new grade extends Migration

{

/**

* Run the migrations.

*

* @render void

*/

public function upwards ()

{

Schema :: create ( ' flights ' , function ( Design $tabular array ) {

$table -> id ();

$table -> string ( ' name ' );

$table -> cord ( ' airline ' );

$table -> timestamps ();

});

}

/**

* Opposite the migrations.

*

* @return void

*/

public function down ()

{

Schema :: drib ( ' flights ' );

}

};

Setting The Migration Connection

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

                                        

/**

* The database connectedness that should be used by the migration.

*

* @var string

*/

protected $connection = ' pgsql ' ;

/**

* Run the migrations.

*

* @return void

*/

public office up ()

{

//

}

Running Migrations

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

                                        

php artisan migrate

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

                                        

php artisan migrate:condition

Forcing Migrations To Run In Production

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

                                        

php artisan migrate --strength

Rolling Back Migrations

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

                                        

php artisan drift:rollback

You may roll dorsum a limited number of migrations by providing the step choice to the rollback command. For case, the post-obit command will roll dorsum the last five migrations:

                                        

php artisan migrate:rollback --step=5

The drift:reset command will ringlet back all of your awarding's migrations:

                                        

php artisan migrate:reset

Coil Back & Migrate Using A Single Control

The migrate:refresh command volition roll back all of your migrations and then execute the migrate command. This command finer re-creates your unabridged database:

                                        

php artisan migrate:refresh

# Refresh the database and run all database seeds...

php artisan migrate:refresh --seed

You lot may roll back and re-drift a express number of migrations by providing the step option to the refresh command. For instance, the following control will curl dorsum and re-migrate the last five migrations:

                                        

php artisan migrate:refresh --step=five

Drop All Tables & Migrate

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

                                        

php artisan migrate:fresh

php artisan migrate:fresh --seed

{annotation} The migrate:fresh command volition drop all database tables regardless of their prefix. This control should exist used with caution when developing on a database that is shared with other applications.

Tables

Creating Tables

To create a new database table, utilise the create method on the Schema facade. The create method accepts ii arguments: the first is the proper noun of the tabular array, while the second is a closure which receives a Blueprint object that may be used to define the new tabular array:

                                        

use Illuminate\Database\Schema\ Blueprint ;

use Illuminate\Support\Facades\ Schema ;

Schema :: create ( ' users ' , office ( Design $table ) {

$table -> id ();

$table -> cord ( ' name ' );

$table -> string ( ' email ' );

$table -> timestamps ();

});

When creating the tabular array, you may utilise whatever of the schema builder's column methods to define the table's columns.

Checking For Table / Column Being

Yous may bank check for the being 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 & Tabular array Options

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

                                        

Schema :: connection ( ' sqlite ' ) -> create ( ' users ' , function ( Pattern $table ) {

$table -> id ();

});

In addition, a few other backdrop and methods may be used to define other aspects of the tabular array'south creation. The engine belongings may be used to specify the table'south storage engine when using MySQL:

                                        

Schema :: create ( ' users ' , function ( Design $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 ' ;

$tabular array ->collation = ' utf8mb4_unicode_ci ' ;

// ...

});

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

                                        

Schema :: create ( ' calculations ' , part ( Design $table ) {

$table -> temporary ();

// ...

});

Updating Tables

The table method on the Schema facade may be used to update existing tables. Similar the create method, the table method accepts 2 arguments: the name of the table and a closure that receives a Blueprint case you lot may use to add columns or indexes to the table:

                                        

use Illuminate\Database\Schema\ Blueprint ;

use Illuminate\Back up\Facades\ Schema ;

Schema :: table ( ' users ' , part ( Blueprint $table ) {

$table -> integer ( ' votes ' );

});

Renaming / Dropping Tables

To rename an existing database tabular array, use the rename method:

                                        

employ Illuminate\Support\Facades\ Schema ;

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

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

                                        

Schema :: drib ( ' users ' );

Schema :: dropIfExists ( ' users ' );

Renaming Tables With Foreign Keys

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

Columns

Creating Columns

The table method on the Schema facade may exist used to update existing tables. Like the create method, the table method accepts 2 arguments: the proper name of the table and a closure that receives an Illuminate\Database\Schema\Blueprint case you may apply 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 represent to the different types of columns yous can add to your database tables. Each of the available methods are listed in the table below:

bigIncrements()

The bigIncrements method creates an auto-incrementing UNSIGNED BIGINT (main key) equivalent cavalcade:

                                        

$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 cavalcade 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 cavalcade with an optional precision (total digits):

                                        

$table -> dateTime ( ' created_at ' , $precision = 0 );

engagement()

The date method creates a Date equivalent column:

                                        

$table -> appointment ( ' 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 cavalcade with the given precision (total digits) and calibration (decimal digits):

                                        

$table -> double ( ' amount ' , eight , 2 );

enum()

The enum method creates a ENUM equivalent cavalcade with the given valid values:

                                        

$tabular array -> enum ( ' difficulty ' , [ ' easy ' , ' hard ' ]);

float()

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

                                        

$table -> float ( ' amount ' , eight , 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 cavalcade for a given model form:

                                        

$table -> foreignIdFor ( User :: class );

foreignUuid()

The foreignUuid method creates a UUID equivalent column:

                                        

$tabular array -> foreignUuid ( ' user_id ' );

geometryCollection()

The geometryCollection method creates a GEOMETRYCOLLECTION equivalent cavalcade:

                                        

$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. Past default, the method volition create an id column; notwithstanding, you may laissez passer a column proper noun if you would like to assign a different name to the cavalcade:

                                        

$table -> id ();

increments()

The increments method creates an auto-incrementing UNSIGNED INTEGER equivalent column every bit a chief 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 ( ' clarification ' );

macAddress()

The macAddress method creates a column that is intended to concur a MAC address. Some database systems, such as PostgreSQL, have a defended 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 automobile-incrementing UNSIGNED MEDIUMINT equivalent column every bit 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 {cavalcade}_id UNSIGNED BIGINT equivalent column and a {cavalcade}_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 exist 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:

                                        

$tabular array -> 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":

                                        

$tabular array -> nullableMorphs ( ' taggable ' );

nullableUuidMorphs()

The method is similar to the uuidMorphs method; however, the columns that are created volition 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 shop the current "recall me" authentication token:

                                        

$table -> rememberToken ();

set()

The fix method creates a Ready equivalent column with the given list of valid values:

                                        

$tabular array -> set ( ' flavors ' , [ ' strawberry ' , ' vanilla ' ]);

smallIncrements()

The smallIncrements method creates an car-incrementing UNSIGNED SMALLINT equivalent column as a principal key:

                                        

$table -> smallIncrements ( ' id ' );

smallInteger()

The smallInteger method creates a SMALLINT equivalent column:

                                        

$tabular array -> smallInteger ( ' votes ' );

softDeletesTz()

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

                                        

$tabular array -> softDeletesTz ( $column = ' deleted_at ' , $precision = 0 );

softDeletes()

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

                                        

$tabular array -> softDeletes ( $cavalcade = ' deleted_at ' , $precision = 0 );

cord()

The string method creates a VARCHAR equivalent cavalcade of the given length:

                                        

$table -> string ( ' proper name ' , 100 );

text()

The text method creates a TEXT equivalent cavalcade:

                                        

$tabular array -> text ( ' clarification ' );

timeTz()

The timeTz method creates a Time (with timezone) equivalent column with an optional precision (full digits):

                                        

$table -> timeTz ( ' sunrise ' , $precision = 0 );

time()

The fourth dimension method creates a TIME equivalent column with an optional precision (full digits):

                                        

$tabular array -> time ( ' sunrise ' , $precision = 0 );

timestampTz()

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

                                        

$table -> timestampTz ( ' added_at ' , $precision = 0 );

timestamp()

The timestamp method creates a TIMESTAMP equivalent cavalcade with an optional precision (total digits):

                                        

$tabular array -> timestamp ( ' added_at ' , $precision = 0 );

timestampsTz()

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

                                        

$table -> timestampsTz ( $precision = 0 );

timestamps()

The timestamps method creates created_at and updated_at TIMESTAMP equivalent columns with an optional precision (total digits):

                                        

$table -> timestamps ( $precision = 0 );

tinyIncrements()

The tinyIncrements method creates an auto-incrementing UNSIGNED TINYINT equivalent column as a chief key:

                                        

$table -> tinyIncrements ( ' id ' );

tinyInteger()

The tinyInteger method creates a TINYINT equivalent column:

                                        

$table -> tinyInteger ( ' votes ' );

tinyText()

The tinyText method creates a TINYTEXT equivalent column:

                                        

$table -> tinyText ( ' notes ' );

unsignedBigInteger()

The unsignedBigInteger method creates an UNSIGNED BIGINT equivalent column:

                                        

$table -> unsignedBigInteger ( ' votes ' );

unsignedDecimal()

The unsignedDecimal method creates an UNSIGNED DECIMAL equivalent column with an optional precision (total digits) and calibration (decimal digits):

                                        

$table -> unsignedDecimal ( ' corporeality ' , $precision = 8 , $scale = 2 );

unsignedInteger()

The unsignedInteger method creates an UNSIGNED INTEGER equivalent cavalcade:

                                        

$tabular array -> unsignedInteger ( ' votes ' );

unsignedMediumInteger()

The unsignedMediumInteger method creates an UNSIGNED MEDIUMINT equivalent column:

                                        

$table -> unsignedMediumInteger ( ' votes ' );

unsignedSmallInteger()

The unsignedSmallInteger method creates an UNSIGNED SMALLINT equivalent column:

                                        

$table -> unsignedSmallInteger ( ' votes ' );

unsignedTinyInteger()

The unsignedTinyInteger method creates an UNSIGNED TINYINT equivalent column:

                                        

$table -> unsignedTinyInteger ( ' votes ' );

uuidMorphs()

The uuidMorphs method is a convenience method that adds a {cavalcade}_id CHAR(36) 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 human relationship that use UUID identifiers. In the following example, taggable_id and taggable_type columns would be created:

                                        

$table -> uuidMorphs ( ' taggable ' );

uuid()

The uuid method creates a UUID equivalent column:

                                        

$table -> uuid ( ' id ' );

twelvemonth()

The twelvemonth method creates a Yr equivalent column:

                                        

$table -> year ( ' birth_year ' );

Column Modifiers

In improver to the column types listed to a higher place, in that location are several column "modifiers" y'all may apply when adding a column to a database table. For example, to make the column "nullable", you may use the nullable method:

                                        

use Illuminate\Database\Schema\ Design ;

use Illuminate\Support\Facades\ Schema ;

Schema :: table ( ' users ' , function ( Blueprint $tabular array ) {

$table -> string ( ' email ' ) -> nullable ();

});

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

Modifier Description
->after('column') Place the cavalcade "after" another column (MySQL).
->autoIncrement() Set up INTEGER columns equally auto-incrementing (primary key).
->charset('utf8mb4') Specify a character set for the column (MySQL).
->collation('utf8mb4_unicode_ci') Specify a collation for the column (MySQL/PostgreSQL/SQL Server).
->comment('my comment') Add a annotate to a column (MySQL/PostgreSQL).
->default($value) Specify a "default" value for the column.
->first() Identify the column "first" in the table (MySQL).
->from($integer) Set the starting value of an auto-incrementing field (MySQL / PostgreSQL).
->invisible() Make the cavalcade "invisible" to SELECT * queries (MySQL).
->nullable($value = true) Let Naught values to be inserted into the cavalcade.
->storedAs($expression) Create a stored generated column (MySQL / PostgreSQL).
->unsigned() Prepare INTEGER columns as UNSIGNED (MySQL).
->useCurrent() Ready TIMESTAMP columns to use CURRENT_TIMESTAMP as default value.
->useCurrentOnUpdate() Fix TIMESTAMP columns to use CURRENT_TIMESTAMP when a record is updated.
->virtualAs($expression) Create a virtual generated cavalcade (MySQL).
->generatedAs($expression) Create an identity cavalcade with specified sequence options (PostgreSQL).
->ever() Defines the precedence of sequence values over input for an identity column (PostgreSQL).
->isGeometry() Set spatial column type to geometry - the default type is geography (PostgreSQL).

Default Expressions

The default modifier accepts a value or an Illuminate\Database\Query\Expression case. Using an Expression case will prevent Laravel from wrapping the value in quotes and allow you to use database specific functions. I situation where this is particularly useful is when yous need to assign default values to JSON columns:

                                        

<?php

employ Illuminate\Back up\Facades\ Schema ;

use Illuminate\Database\Schema\ Blueprint ;

utilize Illuminate\Database\Query\ Expression ;

employ Illuminate\Database\Migrations\ Migration ;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up ()

{

Schema :: create ( ' flights ' , function ( Blueprint $table ) {

$table -> id ();

$tabular array -> json ( ' movies ' ) -> default ( new Expression ( ' (JSON_ARRAY()) ' ));

$tabular array -> timestamps ();

});

}

};

{notation} Support for default expressions depends on your database driver, database version, and the field blazon. Please refer to your database'southward documentation.

Cavalcade Society

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

                                        

$table -> after ( ' countersign ' , function ( $table ) {

$table -> string ( ' address_line1 ' );

$table -> cord ( ' address_line2 ' );

$table -> string ( ' city ' );

});

Modifying Columns

Prerequisites

Before modifying a cavalcade, yous must install the doctrine/dbal 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:

                                        

composer require doctrine / dbal

If you program to modify columns created using the timestamp method, you must as well add the following configuration to your application'south config/database.php configuration file:

                                        

apply Illuminate\Database\DBAL\ TimestampType ;

' dbal ' => [

' types ' => [

' timestamp ' => TimestampType :: class ,

],

],

{note} If your application is using Microsoft SQL Server, please ensure that you install doctrine/dbal:^3.0.

Updating Column Attributes

The change method allows you to modify the blazon 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'southward increase the size of the name column from 25 to fifty. To achieve this, we simply define the new land of the cavalcade and and so telephone call the change method:

                                        

Schema :: tabular array ( ' users ' , function ( Blueprint $table ) {

$table -> cord ( ' proper name ' , 50 ) -> alter ();

});

We could too modify a column to be nullable:

                                        

Schema :: tabular array ( ' users ' , part ( Blueprint $tabular array ) {

$table -> string ( ' proper noun ' , 50 ) -> nullable () -> change ();

});

{note} The post-obit column types tin exist modified: bigInteger, binary, boolean, char, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger, unsignedSmallInteger, and uuid. To modify a timestamp column blazon a Doctrine type must exist registered.

Renaming Columns

To rename a column, you may employ the renameColumn method provided by the schema builder pattern. Before renaming a column, ensure that you have installed the doctrine/dbal library via the Composer package manager:

                                        

Schema :: table ( ' users ' , part ( Design $table ) {

$table -> renameColumn ( ' from ' , ' to ' );

});

{notation} Renaming an enum column is not currently supported.

Dropping Columns

To drop a column, you lot may utilize the dropColumn method on the schema builder blueprint. If your awarding is utilizing an SQLite database, you lot must install the doctrine/dbal package via the Composer package manager before the dropColumn method may exist used:

                                        

Schema :: tabular array ( ' users ' , function ( Blueprint $tabular array ) {

$table -> dropColumn ( ' votes ' );

});

You may drib multiple columns from a table by passing an assortment of cavalcade names to the dropColumn method:

                                        

Schema :: table ( ' users ' , function ( Design $table ) {

$table -> dropColumn ([ ' votes ' , ' avatar ' , ' location ' ]);

});

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

Bachelor Command Aliases

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

Command Description
$tabular array->dropMorphs('morphable'); Drop the morphable_id and morphable_type columns.
$tabular array->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.

Indexes

Creating Indexes

The Laravel schema builder supports several types of indexes. The following instance creates a new e-mail cavalcade and specifies that its values should exist unique. To create the index, we tin chain the unique method onto the column definition:

                                        

use Illuminate\Database\Schema\ Blueprint ;

utilise Illuminate\Support\Facades\ Schema ;

Schema :: table ( ' users ' , function ( Pattern $table ) {

$tabular array -> string ( ' email ' ) -> unique ();

});

Alternatively, y'all may create the index afterward defining the cavalcade. To do and then, you should call the unique method on the schema architect pattern. This method accepts the name of the column that should receive a unique index:

                                        

$tabular array -> unique ( ' email ' );

Y'all may fifty-fifty pass an array of columns to an index method to create a compound (or blended) index:

                                        

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

When creating an index, Laravel will automatically generate an alphabetize proper noun based on the tabular array, column names, and the alphabetize blazon, but you may laissez passer a 2d argument to the method to specify the index name yourself:

                                        

$table -> unique ( ' electronic mail ' , ' unique_email ' );

Bachelor Alphabetize Types

Laravel's schema builder pattern 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 proper noun will be derived from the names of the table and column(s) used for the index, as well as the index blazon. Each of the bachelor alphabetize methods is described in the tabular array beneath:

Control Clarification
$table->main('id'); Adds a primary key.
$table->primary(['id', 'parent_id']); Adds composite keys.
$table->unique('email'); Adds a unique index.
$tabular array->index('state'); Adds an index.
$table->fullText('body'); Adds a full text alphabetize (MySQL/PostgreSQL).
$table->fullText('body')->linguistic communication('english'); Adds a total text index of the specified linguistic communication (PostgreSQL).
$table->spatialIndex('location'); Adds a spatial index (except SQLite).

Index Lengths & MySQL / MariaDB

Past default, Laravel uses the utf8mb4 character set. If you are running a version of MySQL older than the 5.7.seven release or MariaDB older than the 10.two.two release, you may need to manually configure the default string length generated by migrations in society for MySQL to create indexes for them. Y'all may configure the default string length by calling the Schema::defaultStringLength method within the boot method of your App\Providers\AppServiceProvider form:

                                        

use Illuminate\Support\Facades\ Schema ;

/**

* Bootstrap any application services.

*

* @return void

*/

public office kicking ()

{

Schema :: defaultStringLength ( 191 );

}

Alternatively, y'all may enable the innodb_large_prefix option for your database. Refer to your database'due south documentation for instructions on how to properly enable this option.

Renaming Indexes

To rename an index, y'all may apply the renameIndex method provided by the schema builder pattern. This method accepts the current index proper name as its starting time argument and the desired proper name as its second argument:

                                        

$table -> renameIndex ( ' from ' , ' to ' )

Dropping Indexes

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

Command Description
$table->dropPrimary('users_id_primary'); Drop a primary primal from the "users" table.
$table->dropUnique('users_email_unique'); Drop a unique index from the "users" table.
$tabular array->dropIndex('geo_state_index'); Drop a basic index from the "geo" table.
$table->dropFullText('posts_body_fulltext'); Drop a full text index from the "posts" table.
$table->dropSpatialIndex('geo_location_spatialindex'); Drop a spatial index from the "geo" tabular array (except SQLite).

If y'all pass an array of columns into a method that drops indexes, the conventional index proper name will exist generated based on the table name, columns, and alphabetize type:

                                        

Schema :: table ( ' geo ' , part ( Blueprint $table ) {

$table -> dropIndex ([ ' country ' ]); // Drops alphabetize 'geo_state_index'

});

Foreign Key Constraints

Laravel also provides support for creating foreign fundamental constraints, which are used to strength referential integrity at the database level. For instance, let's ascertain a user_id column on the posts table that references the id column on a users table:

                                        

apply Illuminate\Database\Schema\ Blueprint ;

use Illuminate\Back up\Facades\ Schema ;

Schema :: tabular array ( ' posts ' , function ( Pattern $table ) {

$table -> unsignedBigInteger ( ' user_id ' );

$tabular array -> foreign ( ' user_id ' ) -> references ( ' id ' ) -> on ( ' users ' );

});

Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better programmer feel. When using the foreignId method to create your cavalcade, the instance above can be rewritten like and so:

                                        

Schema :: table ( ' posts ' , function ( Pattern $tabular array ) {

$tabular array -> foreignId ( ' user_id ' ) -> constrained ();

});

The foreignId method creates an UNSIGNED BIGINT equivalent cavalcade, while the constrained method will use conventions to determine the tabular array and column proper name existence referenced. If your table name does non match Laravel's conventions, you may specify the table proper noun by passing it as an argument to the constrained method:

                                        

Schema :: table ( ' posts ' , function ( Design $table ) {

$table -> foreignId ( ' user_id ' ) -> constrained ( ' users ' );

});

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

                                        

$table -> foreignId ( ' user_id ' )

-> constrained ()

-> onUpdate ( ' cascade ' )

-> onDelete ( ' pour ' );

An alternative, expressive syntax is also provided for these actions:

Method Description
$table->cascadeOnUpdate(); Updates should cascade.
$table->restrictOnUpdate(); Updates should exist restricted.
$tabular array->cascadeOnDelete(); Deletes should cascade.
$table->restrictOnDelete(); Deletes should be restricted.
$tabular array->nullOnDelete(); Deletes should set up the strange key value to cipher.

Any additional cavalcade modifiers must exist called earlier the constrained method:

                                        

$tabular array -> foreignId ( ' user_id ' )

-> nullable ()

-> constrained ();

Dropping Foreign Keys

To drop a foreign fundamental, y'all may utilise the dropForeign method, passing the name of the strange key constraint to be deleted as an argument. Foreign fundamental constraints utilise the aforementioned naming convention as indexes. In other words, the strange fundamental constraint name is based on the name of the table and the columns in the constraint, followed by a "_foreign" suffix:

                                        

$table -> dropForeign ( ' posts_user_id_foreign ' );

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

                                        

$tabular array -> dropForeign ([ ' user_id ' ]);

Toggling Foreign Central Constraints

You lot may enable or disable foreign primal constraints inside your migrations past using the following methods:

                                        

Schema :: enableForeignKeyConstraints ();

Schema :: disableForeignKeyConstraints ();

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

Events

For convenience, each migration performance will dispatch an result. All of the following events extend the base Illuminate\Database\Events\MigrationEvent class:

Grade Clarification
Illuminate\Database\Events\MigrationsStarted A batch of migrations is about to be executed.
Illuminate\Database\Events\MigrationsEnded A batch of migrations has finished executing.
Illuminate\Database\Events\MigrationStarted A unmarried migration is about to be executed.
Illuminate\Database\Events\MigrationEnded A single migration has finished executing.
Illuminate\Database\Events\SchemaDumped A database schema dump has completed.
Illuminate\Database\Events\SchemaLoaded An existing database schema dump has loaded.

How To Set Default Value In Laravel Migration,

Source: https://laravel.com/docs/9.x/migrations

Posted by: rubinlailme.blogspot.com

0 Response to "How To Set Default Value In Laravel Migration"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel