Full Text Mysql Populate Table Again
Database: Migrations
- Introduction
- Generating Migrations
- Squashing Migrations
- Migration Construction
- Running Migrations
- Rolling Back Migrations
- Tables
- Creating Tables
- Updating Tables
- Renaming / Dropping Tables
- Columns
- Creating Columns
- Available Cavalcade Types
- Column Modifiers
- Modifying Columns
- Dropping Columns
- Indexes
- Creating Indexes
- Renaming Indexes
- Dropping Indexes
- Strange Primal Constraints
- Events
Introduction
Migrations are like version command for your database, allowing your team to ascertain and share the awarding's database schema definition. If yous have ever had to tell a teammate to manually add together a column to their local database schema subsequently pulling in your changes from source control, you lot'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'southward supported database systems. Typically, migrations will use this facade to create and alter database tables and columns.
Generating Migrations
You may use 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 make:migration create_flights_table
Laravel will utilise the name of the migration to endeavor to guess the proper name of the table and whether or not the migration will be creating a new table. If Laravel is able to determine the table proper name from the migration name, Laravel will pre-make full the generated migration file with the specified tabular array. Otherwise, you may only specify the table in the migration file manually.
If you lot would like to specify a custom path for the generated migration, yous may use the --path
pick when executing the make:migration
command. The given path should exist relative to your awarding'southward base path.
{tip} Migration stubs may be customized using stub publishing.
Squashing Migrations
As you build your awarding, you may accumulate more and more migrations over time. This tin can lead to your database/migrations
directory becoming swollen with potentially hundreds of migrations. If you would like, y'all may "squash" your migrations into a single SQL file. To become started, execute the schema:dump
control:
php artisan schema:dump
# Dump the current database schema and clip all existing migrations...
php artisan schema:dump --prune
When you execute this command, Laravel will write a "schema" file to your application'due south database/schema
directory. Now, when you lot effort to drift your database and no other migrations have been executed, Laravel will execute the schema file'due south SQL statements first. After executing the schema file's statements, Laravel volition execute any remaining migrations that were not part of the schema dump.
Y'all should commit your database schema file to source control so that other new developers on your team may rapidly create your awarding's initial database construction.
{note} Migration squashing is only available for the MySQL, PostgreSQL, and SQLite databases and utilizes the database's command-line client. Schema dumps may non 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 downwardly
method should reverse the operations performed by the upwardly
method.
Within both of these methods, you may use the Laravel schema builder to expressively create and alter tables. To acquire well-nigh all of the methods available on the Schema
builder, bank check out its documentation. For example, the following migration creates a flights
table:
<?php
use Illuminate\Database\Migrations\ Migration ;
use Illuminate\Database\Schema\ Design ;
use Illuminate\Support\Facades\ Schema ;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public role upwardly ()
{
Schema :: create ( ' flights ' , function ( Blueprint $table ) {
$tabular array -> id ();
$table -> string ( ' name ' );
$table -> string ( ' airline ' );
$table -> timestamps ();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function downwardly ()
{
Schema :: drib ( ' flights ' );
}
};
Setting The Migration Connection
If your migration will be interacting with a database connection other than your application'southward default database connection, y'all should set the $connection
belongings of your migration:
/**
* The database connection that should be used past the migration.
*
* @var string
*/
protected $connection = ' pgsql ' ;
/**
* Run the migrations.
*
* @render void
*/
public function 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, yous may use the migrate:status
Artisan control:
php artisan migrate:status
Forcing Migrations To Run In Product
Some migration operations are destructive, which means they may cause you to lose data. In society to protect yous from running these commands confronting your product database, y'all will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the --forcefulness
flag:
php artisan drift --strength
Rolling Back Migrations
To roll back the latest migration operation, you may use the rollback
Artisan command. This command rolls back the final "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 stride
option to the rollback
command. For example, the following command volition curl back the terminal five migrations:
php artisan migrate:rollback --step=5
The migrate:reset
command will ringlet back all of your awarding's migrations:
php artisan migrate:reset
Roll Back & Migrate Using A Single Control
The drift:refresh
command will gyre dorsum all of your migrations so execute the migrate
control. This command finer re-creates your entire database:
php artisan drift:refresh
# Refresh the database and run all database seeds...
php artisan migrate:refresh --seed
You may gyre dorsum and re-migrate a express number of migrations by providing the stride
option to the refresh
command. For instance, the following control will roll back and re-drift the last five migrations:
php artisan migrate:refresh --footstep=v
Driblet 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
control will driblet all database tables regardless of their prefix. This command 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, use the create
method on the Schema
facade. The create
method accepts two arguments: the first is the proper name of the table, while the second is a closure which receives a Blueprint
object that may be used to define the new table:
utilise Illuminate\Database\Schema\ Blueprint ;
use Illuminate\Support\Facades\ Schema ;
Schema :: create ( ' users ' , role ( Design $tabular array ) {
$tabular array -> id ();
$table -> cord ( ' name ' );
$table -> string ( ' electronic mail ' );
$table -> timestamps ();
});
When creating the tabular array, you may employ any of the schema builder'due south column methods to ascertain the table's columns.
Checking For Table / Column Existence
You may check for the existence of a tabular array or column using the hasTable
and hasColumn
methods:
if ( Schema :: hasTable ( ' users ' )) {
// The "users" table exists...
}
if ( Schema :: hasColumn ( ' users ' , ' email ' )) {
// The "users" tabular array exists and has an "email" cavalcade...
}
Database Connection & Table Options
If yous want to perform a schema functioning on a database connexion that is not your application's default connection, employ the connectedness
method:
Schema :: connectedness ( ' sqlite ' ) -> create ( ' users ' , part ( Blueprint $table ) {
$table -> id ();
});
In addition, a few other properties and methods may be used to ascertain other aspects of the table's creation. The engine
holding 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 up and collation for the created table when using MySQL:
Schema :: create ( ' users ' , function ( Blueprint $tabular array ) {
$table ->charset = ' utf8mb4 ' ;
$tabular array ->collation = ' utf8mb4_unicode_ci ' ;
// ...
});
The temporary
method may be used to bespeak that the table should be "temporary". Temporary tables are simply visible to the electric current connexion's database session and are dropped automatically when the connection is closed:
Schema :: create ( ' calculations ' , function ( Design $table ) {
$tabular array -> temporary ();
// ...
});
Updating Tables
The table
method on the Schema
facade may exist used to update existing tables. Similar the create
method, the table
method accepts two arguments: the proper noun of the table and a closure that receives a Blueprint
example you may utilize to add columns or indexes to the table:
use Illuminate\Database\Schema\ Blueprint ;
use Illuminate\Support\Facades\ Schema ;
Schema :: table ( ' users ' , role ( Blueprint $tabular array ) {
$table -> integer ( ' votes ' );
});
Renaming / Dropping Tables
To rename an existing database table, employ the rename
method:
use Illuminate\Support\Facades\ Schema ;
Schema :: rename ( $from , $to );
To drib an existing table, you may utilize the drib
or dropIfExists
methods:
Schema :: drop ( ' users ' );
Schema :: dropIfExists ( ' users ' );
Renaming Tables With Foreign Keys
Before renaming a tabular array, you should verify that whatsoever foreign key constraints on the table take an explicit name in your migration files instead of letting Laravel assign a convention based name. Otherwise, the foreign primal constraint proper name will refer to the one-time table name.
Columns
Creating Columns
The table
method on the Schema
facade may exist used to update existing tables. Similar the create
method, the table
method accepts two arguments: the proper noun of the table and a closure that receives an Illuminate\Database\Schema\Blueprint
case yous may use to add columns to the table:
use Illuminate\Database\Schema\ Blueprint ;
utilize Illuminate\Support\Facades\ Schema ;
Schema :: table ( ' users ' , part ( Blueprint $table ) {
$table -> integer ( ' votes ' );
});
Available Column Types
The schema builder blueprint offers a variety of methods that correspond to the unlike types of columns you tin add together 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
(primary key) equivalent cavalcade:
$table -> bigIncrements ( ' id ' );
bigInteger()
The bigInteger
method creates a BIGINT
equivalent column:
$table -> bigInteger ( ' votes ' );
binary()
The binary
method creates a Hulk
equivalent column:
$table -> binary ( ' photograph ' );
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 ( ' proper 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):
$tabular array -> dateTime ( ' created_at ' , $precision = 0 );
engagement()
The date
method creates a Engagement
equivalent column:
$table -> engagement ( ' 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 = two );
double()
The double
method creates a DOUBLE
equivalent column with the given precision (full 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 Bladder
equivalent cavalcade with the given precision (total digits) and scale (decimal digits):
$table -> float ( ' amount ' , 8 , ii );
foreignId()
The foreignId
method creates an UNSIGNED BIGINT
equivalent column:
$table -> foreignId ( ' user_id ' );
foreignIdFor()
The foreignIdFor
method adds a {cavalcade}_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 laissez passer a column name if y'all would like to assign a different name to the column:
$table -> id ();
increments()
The increments
method creates an machine-incrementing UNSIGNED INTEGER
equivalent cavalcade as a primary primal:
$table -> increments ( ' id ' );
integer()
The integer
method creates an INTEGER
equivalent column:
$tabular array -> 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 cavalcade:
$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 equally PostgreSQL, have a dedicated column type for this type of information. Other database systems will use a cord equivalent column:
$tabular array -> macAddress ( ' device ' );
mediumIncrements()
The mediumIncrements
method creates an auto-incrementing UNSIGNED MEDIUMINT
equivalent column as a master central:
$table -> mediumIncrements ( ' id ' );
mediumInteger()
The mediumInteger
method creates a MEDIUMINT
equivalent cavalcade:
$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 {cavalcade}_type
VARCHAR
equivalent cavalcade.
This method is intended to be used when defining the columns necessary for a polymorphic Eloquent human relationship. In the post-obit example, taggable_id
and taggable_type
columns would exist created:
$table -> morphs ( ' taggable ' );
multiLineString()
The multiLineString
method creates a MULTILINESTRING
equivalent column:
$tabular array -> multiLineString ( ' positions ' );
multiPoint()
The multiPoint
method creates a MULTIPOINT
equivalent cavalcade:
$tabular array -> multiPoint ( ' positions ' );
multiPolygon()
The multiPolygon
method creates a MULTIPOLYGON
equivalent cavalcade:
$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; yet, the columns that are created will be "nullable":
$table -> nullableMorphs ( ' taggable ' );
nullableUuidMorphs()
The method is similar to the uuidMorphs method; still, the columns that are created will be "nullable":
$tabular array -> nullableUuidMorphs ( ' taggable ' );
point()
The point
method creates a Betoken
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 "call back me" authentication token:
$table -> rememberToken ();
fix()
The set
method creates a SET
equivalent column with the given list of valid values:
$table -> set ( ' flavors ' , [ ' strawberry ' , ' vanilla ' ]);
smallIncrements()
The smallIncrements
method creates an auto-incrementing UNSIGNED SMALLINT
equivalent column equally a primary key:
$tabular array -> smallIncrements ( ' id ' );
smallInteger()
The smallInteger
method creates a SMALLINT
equivalent column:
$table -> smallInteger ( ' votes ' );
softDeletesTz()
The softDeletesTz
method adds a nullable deleted_at
TIMESTAMP
(with timezone) equivalent column with an optional precision (total digits). This column is intended to store the deleted_at
timestamp needed for Eloquent's "soft delete" functionality:
$table -> softDeletesTz ( $cavalcade = ' deleted_at ' , $precision = 0 );
softDeletes()
The softDeletes
method adds a nullable deleted_at
TIMESTAMP
equivalent cavalcade with an optional precision (total digits). This column is intended to store the deleted_at
timestamp needed for Eloquent'southward "soft delete" functionality:
$tabular array -> softDeletes ( $column = ' deleted_at ' , $precision = 0 );
string()
The string
method creates a VARCHAR
equivalent column of the given length:
$table -> string ( ' name ' , 100 );
text()
The text
method creates a TEXT
equivalent cavalcade:
$table -> text ( ' description ' );
timeTz()
The timeTz
method creates a Fourth dimension
(with timezone) equivalent column with an optional precision (total digits):
$tabular array -> timeTz ( ' sunrise ' , $precision = 0 );
fourth dimension()
The time
method creates a Time
equivalent column with an optional precision (total digits):
$table -> time ( ' sunrise ' , $precision = 0 );
timestampTz()
The timestampTz
method creates a TIMESTAMP
(with timezone) equivalent cavalcade 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):
$table -> timestamp ( ' added_at ' , $precision = 0 );
timestampsTz()
The timestampsTz
method creates created_at
and updated_at
TIMESTAMP
(with timezone) equivalent columns with an optional precision (full 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 motorcar-incrementing UNSIGNED TINYINT
equivalent column as a master 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 cavalcade with an optional precision (total digits) and calibration (decimal digits):
$table -> unsignedDecimal ( ' amount ' , $precision = 8 , $scale = two );
unsignedInteger()
The unsignedInteger
method creates an UNSIGNED INTEGER
equivalent column:
$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:
$tabular array -> unsignedSmallInteger ( ' votes ' );
unsignedTinyInteger()
The unsignedTinyInteger
method creates an UNSIGNED TINYINT
equivalent cavalcade:
$table -> unsignedTinyInteger ( ' votes ' );
uuidMorphs()
The uuidMorphs
method is a convenience method that adds a {column}_id
CHAR(36)
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 human relationship that use UUID identifiers. In the post-obit example, taggable_id
and taggable_type
columns would exist created:
$tabular array -> uuidMorphs ( ' taggable ' );
uuid()
The uuid
method creates a UUID
equivalent column:
$table -> uuid ( ' id ' );
twelvemonth()
The year
method creates a YEAR
equivalent column:
$table -> year ( ' birth_year ' );
Column Modifiers
In addition to the column types listed higher up, there are several column "modifiers" you may use when adding a column to a database table. For example, to make the column "nullable", y'all may utilize the nullable
method:
use Illuminate\Database\Schema\ Blueprint ;
use Illuminate\Support\Facades\ Schema ;
Schema :: table ( ' users ' , part ( Blueprint $table ) {
$table -> string ( ' e-mail ' ) -> nullable ();
});
The post-obit table contains all of the available column modifiers. This listing does not include index modifiers:
Modifier | Clarification |
---|---|
->after('column') | Place the column "after" another column (MySQL). |
->autoIncrement() | Set INTEGER columns every bit auto-incrementing (primary primal). |
->charset('utf8mb4') | Specify a grapheme set for the column (MySQL). |
->collation('utf8mb4_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 cavalcade. |
->kickoff() | Identify the cavalcade "beginning" in the table (MySQL). |
->from($integer) | Set the starting value of an car-incrementing field (MySQL / PostgreSQL). |
->invisible() | Make the cavalcade "invisible" to SELECT * queries (MySQL). |
->nullable($value = truthful) | Allow Goose egg values to be inserted into the column. |
->storedAs($expression) | Create a stored generated column (MySQL / PostgreSQL). |
->unsigned() | Set INTEGER columns equally UNSIGNED (MySQL). |
->useCurrent() | Set TIMESTAMP columns to employ CURRENT_TIMESTAMP as default value. |
->useCurrentOnUpdate() | Gear up TIMESTAMP columns to apply CURRENT_TIMESTAMP when a record is updated. |
->virtualAs($expression) | Create a virtual generated column (MySQL). |
->generatedAs($expression) | Create an identity column with specified sequence options (PostgreSQL). |
->ever() | Defines the precedence of sequence values over input for an identity column (PostgreSQL). |
->isGeometry() | Gear up spatial column type to geometry - the default blazon is geography (PostgreSQL). |
Default Expressions
The default
modifier accepts a value or an Illuminate\Database\Query\Expression
instance. Using an Expression
instance will forestall Laravel from wrapping the value in quotes and allow yous to utilise database specific functions. I situation where this is especially useful is when you need to assign default values to JSON columns:
<?php
use Illuminate\Back up\Facades\ Schema ;
use Illuminate\Database\Schema\ Blueprint ;
use Illuminate\Database\Query\ Expression ;
utilise Illuminate\Database\Migrations\ Migration ;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up ()
{
Schema :: create ( ' flights ' , part ( Blueprint $table ) {
$table -> id ();
$table -> json ( ' movies ' ) -> default ( new Expression ( ' (JSON_ARRAY()) ' ));
$table -> timestamps ();
});
}
};
{annotation} Support for default expressions depends on your database commuter, database version, and the field type. Please refer to your database'due south documentation.
Column Order
When using the MySQL database, the after
method may exist used to add together columns afterward an existing column in the schema:
$table -> afterward ( ' password ' , part ( $tabular array ) {
$table -> string ( ' address_line1 ' );
$tabular array -> cord ( ' address_line2 ' );
$table -> string ( ' city ' );
});
Modifying Columns
Prerequisites
Before modifying a column, yous must install the doctrine/dbal
package using the Composer parcel manager. The Doctrine DBAL library is used to determine the electric current land of the column and to create the SQL queries needed to brand the requested changes to your column:
composer crave doctrine / dbal
If you lot plan to modify columns created using the timestamp
method, yous must too add the following configuration to your application's config/database.php
configuration file:
utilise Illuminate\Database\DBAL\ TimestampType ;
' dbal ' => [
' types ' => [
' timestamp ' => TimestampType :: class ,
],
],
{note} If your application is using Microsoft SQL Server, delight ensure that you install
doctrine/dbal:^3.0
.
Updating Cavalcade Attributes
The change
method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a string
cavalcade. To see the alter
method in action, let'southward increase the size of the name
column from 25 to 50. To accomplish this, we simply define the new state of the column and so call the alter
method:
Schema :: table ( ' users ' , function ( Design $table ) {
$table -> string ( ' proper noun ' , 50 ) -> modify ();
});
We could also alter a column to be nullable:
Schema :: table ( ' users ' , function ( Pattern $table ) {
$table -> cord ( ' name ' , 50 ) -> nullable () -> change ();
});
{note} The following column types can exist modified:
bigInteger
,binary
,boolean
,char
,date
,dateTime
,dateTimeTz
,decimal
,integer
,json
,longText
,mediumText
,smallInteger
,string
,text
,time
,unsignedBigInteger
,unsignedInteger
,unsignedSmallInteger
, anduuid
. To modify atimestamp
column blazon a Doctrine type must exist registered.
Renaming Columns
To rename a column, y'all may apply the renameColumn
method provided by the schema builder blueprint. Before renaming a cavalcade, ensure that you take installed the doctrine/dbal
library via the Composer package director:
Schema :: table ( ' users ' , function ( Blueprint $table ) {
$table -> renameColumn ( ' from ' , ' to ' );
});
{note} Renaming an
enum
column is not currently supported.
Dropping Columns
To driblet a column, y'all may use the dropColumn
method on the schema builder blueprint. If your application is utilizing an SQLite database, you must install the doctrine/dbal
package via the Composer bundle manager before the dropColumn
method may be used:
Schema :: table ( ' users ' , function ( Blueprint $table ) {
$table -> dropColumn ( ' votes ' );
});
You may drib multiple columns from a table by passing an array of column names to the dropColumn
method:
Schema :: table ( ' users ' , part ( Pattern $table ) {
$table -> dropColumn ([ ' votes ' , ' avatar ' , ' location ' ]);
});
{notation} Dropping or modifying multiple columns inside a unmarried migration while using an SQLite database is non supported.
Available Command Aliases
Laravel provides several convenient methods related to dropping common types of columns. Each of these methods is described in the tabular array below:
Control | Description |
---|---|
$table->dropMorphs('morphable'); | Drop the morphable_id and morphable_type columns. |
$table->dropRememberToken(); | Drop the remember_token cavalcade. |
$table->dropSoftDeletes(); | Drop the deleted_at cavalcade. |
$table->dropSoftDeletesTz(); | Alias of dropSoftDeletes() method. |
$table->dropTimestamps(); | Drop the created_at and updated_at columns. |
$tabular array->dropTimestampsTz(); | Alias of dropTimestamps() method. |
Indexes
Creating Indexes
The Laravel schema architect supports several types of indexes. The following example creates a new email
column and specifies that its values should be unique. To create the index, nosotros can chain the unique
method onto the cavalcade definition:
use Illuminate\Database\Schema\ Blueprint ;
use Illuminate\Back up\Facades\ Schema ;
Schema :: table ( ' users ' , role ( Design $table ) {
$table -> string ( ' e-mail ' ) -> unique ();
});
Alternatively, yous may create the index after defining the column. To do so, you should call the unique
method on the schema builder blueprint. This method accepts the proper name of the column that should receive a unique alphabetize:
$table -> unique ( ' email ' );
Yous may fifty-fifty pass an assortment 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 index name based on the tabular array, column names, and the index blazon, but y'all may pass a 2nd argument to the method to specify the index name yourself:
$table -> unique ( ' e-mail ' , ' unique_email ' );
Available Alphabetize Types
Laravel's schema architect pattern class provides methods for creating each blazon of index supported past Laravel. Each alphabetize method accepts an optional 2d argument to specify the proper name of the index. If omitted, the name volition be derived from the names of the tabular array and column(southward) used for the index, as well as the index type. Each of the available index methods is described in the table beneath:
Command | Clarification |
---|---|
$table->main('id'); | Adds a principal key. |
$table->primary(['id', 'parent_id']); | Adds composite keys. |
$table->unique('electronic mail'); | Adds a unique index. |
$tabular array->alphabetize('state'); | Adds an index. |
$table->fullText('body'); | Adds a total text index (MySQL/PostgreSQL). |
$tabular array->fullText('body')->language('english'); | Adds a full text index of the specified language (PostgreSQL). |
$table->spatialIndex('location'); | Adds a spatial index (except SQLite). |
Alphabetize Lengths & MySQL / MariaDB
By default, Laravel uses the utf8mb4
graphic symbol fix. If you are running a version of MySQL older than the v.7.seven release or MariaDB older than the x.2.ii release, you may demand to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure the default string length past calling the Schema::defaultStringLength
method within the boot
method of your App\Providers\AppServiceProvider
class:
use Illuminate\Support\Facades\ Schema ;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot ()
{
Schema :: defaultStringLength ( 191 );
}
Alternatively, you lot may enable the innodb_large_prefix
option for your database. Refer to your database's documentation for instructions on how to properly enable this choice.
Renaming Indexes
To rename an index, you may use the renameIndex
method provided by the schema builder blueprint. This method accepts the electric current index proper name as its first argument and the desired proper noun as its 2d argument:
$table -> renameIndex ( ' from ' , ' to ' )
Dropping Indexes
To drib an index, y'all must specify the index's name. By default, Laravel automatically assigns an index name based on the tabular array name, the name of the indexed column, and the index type. Here are some examples:
Control | Description |
---|---|
$table->dropPrimary('users_id_primary'); | Drib a principal primal from the "users" table. |
$table->dropUnique('users_email_unique'); | Drop a unique alphabetize from the "users" table. |
$table->dropIndex('geo_state_index'); | Drop a bones index from the "geo" table. |
$table->dropFullText('posts_body_fulltext'); | Drop a full text alphabetize from the "posts" table. |
$table->dropSpatialIndex('geo_location_spatialindex'); | Drop a spatial alphabetize from the "geo" table (except SQLite). |
If you laissez passer an array of columns into a method that drops indexes, the conventional index name will be generated based on the table proper noun, columns, and index type:
Schema :: table ( ' geo ' , function ( Pattern $table ) {
$table -> dropIndex ([ ' state ' ]); // Drops index 'geo_state_index'
});
Foreign Key Constraints
Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let'due south define a user_id
cavalcade on the posts
table that references the id
column on a users
table:
use Illuminate\Database\Schema\ Blueprint ;
utilize Illuminate\Support\Facades\ Schema ;
Schema :: table ( ' posts ' , role ( Blueprint $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 ameliorate developer experience. When using the foreignId
method to create your column, the example above tin exist rewritten like so:
Schema :: table ( ' posts ' , office ( Blueprint $table ) {
$table -> foreignId ( ' user_id ' ) -> constrained ();
});
The foreignId
method creates an UNSIGNED BIGINT
equivalent column, while the constrained
method will use conventions to decide the table and column proper noun being referenced. If your table name does not match Laravel's conventions, you may specify the table name by passing it as an statement to the constrained
method:
Schema :: table ( ' posts ' , function ( Design $table ) {
$table -> foreignId ( ' user_id ' ) -> constrained ( ' users ' );
});
Y'all may besides specify the desired activity for the "on delete" and "on update" properties of the constraint:
$table -> foreignId ( ' user_id ' )
-> constrained ()
-> onUpdate ( ' cascade ' )
-> onDelete ( ' cascade ' );
An alternative, expressive syntax is besides 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. |
$table->nullOnDelete(); | Deletes should prepare the foreign key value to null. |
Whatever additional cavalcade modifiers must be called before the constrained
method:
$table -> foreignId ( ' user_id ' )
-> nullable ()
-> constrained ();
Dropping Strange Keys
To drop a strange key, yous may use the dropForeign
method, passing the name of the foreign primal constraint to be deleted as an statement. Foreign central constraints employ the same naming convention equally indexes. In other words, the strange key constraint name is based on the name of the tabular array and the columns in the constraint, followed by a "_foreign" suffix:
$tabular array -> dropForeign ( ' posts_user_id_foreign ' );
Alternatively, yous may pass an array containing the column name that holds the foreign key to the dropForeign
method. The array will be converted to a foreign key constraint name using Laravel's constraint naming conventions:
$table -> dropForeign ([ ' user_id ' ]);
Toggling Foreign Primal Constraints
You may enable or disable foreign cardinal constraints within your migrations past using the post-obit methods:
Schema :: enableForeignKeyConstraints ();
Schema :: disableForeignKeyConstraints ();
{note} SQLite disables foreign primal constraints past default. When using SQLite, make certain to enable foreign key support in your database configuration earlier attempting to create them in your migrations. In addition, SQLite only supports foreign keys upon creation of the table and not when tables are altered.
Events
For convenience, each migration operation will dispatch an outcome. All of the following events extend the base Illuminate\Database\Events\MigrationEvent
grade:
Form | Description |
---|---|
Illuminate\Database\Events\MigrationsStarted | A batch of migrations is nigh to be executed. |
Illuminate\Database\Events\MigrationsEnded | A batch of migrations has finished executing. |
Illuminate\Database\Events\MigrationStarted | A single migration is well-nigh to exist executed. |
Illuminate\Database\Events\MigrationEnded | A unmarried 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. |
davidsonbutheladich.blogspot.com
Source: https://laravel.com/docs/9.x/migrations
0 Response to "Full Text Mysql Populate Table Again"
Post a Comment