banner



How To Change Rails 5.1 Existing Id Column To Uuid

Icon

WARNING You're browsing the documentation for an sometime version of Laravel. Consider upgrading your project to Laravel 9.x.

Database: Migrations

  • Introduction
  • Generating Migrations
  • Migration Structure
  • Running Migrations
    • Rolling Back Migrations
  • Tables
    • Creating Tables
    • Renaming / Dropping Tables
  • Columns
    • Creating Columns
    • Column Modifiers
    • Modifying Columns
    • Dropping Columns
  • Indexes
    • Creating Indexes
    • Renaming Indexes
    • Dropping Indexes
    • Strange Key Constraints

Introduction

Migrations are like version control for your database, allowing your team to easily change and share the application'southward database schema. Migrations are typically paired with Laravel'south schema builder to hands build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.

The Laravel Schema facade provides database doubter support for creating and manipulating tables across all of Laravel's supported database systems.

Generating Migrations

To create a migration, use the make:migration Artisan command:

                                              

php artisan make : migration create_users_table

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

The --table and --create options may too exist used to signal the name of the tabular array and whether the migration will be creating a new tabular array. These options pre-fill the generated migration stub file with the specified table:

                                              

php artisan make : migration create_users_table -- create = users

php artisan make : migration add_votes_to_users_table -- tabular array = users

If you lot would like to specify a custom output path for the generated migration, you lot may use the --path selection when executing the make:migration command. The given path should be relative to your application's base path.

Migration Structure

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

Within both of these methods you may use the Laravel schema builder to expressively create and change tables. To learn nearly all of the methods bachelor on the Schema builder, check out its documentation. For example, this migration case creates a flights table:

                                              

<?php

use Illuminate\Back up\Facades\ Schema ;

use Illuminate\Database\Schema\ Blueprint ;

use Illuminate\Database\Migrations\ Migration ;

class CreateFlightsTable extends Migration

{

/**

* Run the migrations.

*

* @render void

*/

public function up ()

{

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

$table -> increments ( ' id ' );

$table -> cord ( ' name ' );

$tabular array -> cord ( ' airline ' );

$table -> timestamps ();

});

}

/**

* Contrary the migrations.

*

* @render void

*/

public role down ()

{

Schema :: drib ( ' flights ' );

}

}

Running Migrations

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

                                              

php artisan migrate

{note} If you are using the Homestead virtual machine, y'all should run this command from within your virtual machine.

Forcing Migrations To Run In Production

Some migration operations are destructive, which means they may cause yous to lose data. In order to protect yous from running these commands confronting your product database, you volition exist prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the --force flag:

                                              

php artisan migrate -- force

Rolling Back Migrations

To rollback the latest migration performance, you may use the rollback command. This command rolls back the final "batch" of migrations, which may include multiple migration files:

                                              

php artisan migrate : rollback

Yous may rollback a express number of migrations by providing the stride option to the rollback command. For example, the following command will rollback the concluding five migrations:

                                              

php artisan drift : rollback -- step = 5

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

                                              

php artisan drift : reset

Rollback & Drift In Single Control

The drift:refresh control will roll back all of your migrations and then execute the migrate control. This control effectively re-creates your entire database:

                                              

php artisan migrate : refresh

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

php artisan migrate : refresh -- seed

You lot may rollback & re-migrate a express number of migrations by providing the stride pick to the refresh command. For example, the following command will rollback & re-migrate the last five migrations:

                                              

php artisan migrate : refresh -- footstep = 5

Drop All Tables & Drift

The migrate:fresh command will drop all tables from the database so execute the migrate control:

                                              

php artisan migrate : fresh

php artisan migrate : fresh -- seed

Tables

Creating Tables

To create a new database tabular array, use the create method on the Schema facade. The create method accepts two arguments. The first is the name of the table, while the second is a Closure which receives a Blueprint object that may be used to define the new table:

                                              

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

$table -> increments ( ' id ' );

});

Of class, when creating the table, you may utilise any of the schema builder's cavalcade methods to ascertain the table'due south columns.

Checking For Table / Cavalcade Existence

You may hands check for the being of a table or cavalcade using the hasTable and hasColumn methods:

                                              

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

//

}

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

//

}

Database Connectedness & Tabular array Options

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

                                              

Schema :: connexion ( ' foo ' ) -> create ( ' users ' , office ( Blueprint $tabular array ) {

$table -> increments ( ' id ' );

});

You may use the post-obit commands on the schema architect to define the table's options:

Command Description
$tabular array->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).

Renaming / Dropping Tables

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

                                              

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

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

                                              

Schema :: driblet ( ' users ' );

Schema :: dropIfExists ( ' users ' );

Renaming Tables With Foreign Keys

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

Columns

Creating Columns

The table method on the Schema facade may be used to update existing tables. Like the create method, the table method accepts two arguments: the proper noun of the table and a Closure that receives a Design instance you may employ to add columns to the table:

                                              

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

$table -> string ( ' email ' );

});

Available Cavalcade Types

Of grade, the schema architect contains a variety of column types that you may specify when edifice your tables:

Command Description
$table->bigIncrements('id'); Car-incrementing UNSIGNED BIGINT (primary key) equivalent column.
$table->bigInteger('votes'); BIGINT equivalent cavalcade.
$table->binary('data'); BLOB equivalent column.
$table->boolean('confirmed'); BOOLEAN equivalent column.
$table->char('name', 100); CHAR equivalent column with an optional length.
$tabular array->engagement('created_at'); DATE equivalent column.
$table->dateTime('created_at'); DATETIME equivalent column.
$table->dateTimeTz('created_at'); DATETIME (with timezone) equivalent column.
$table->decimal('amount', 8, 2); DECIMAL equivalent cavalcade with a precision (total digits) and scale (decimal digits).
$table->double('amount', viii, two); DOUBLE equivalent column with a precision (total digits) and scale (decimal digits).
$table->enum('level', ['like shooting fish in a barrel', 'hard']); ENUM equivalent column.
$table->float('amount', 8, ii); Bladder equivalent column with a precision (total digits) and scale (decimal digits).
$table->geometry('positions'); GEOMETRY equivalent column.
$tabular array->geometryCollection('positions'); GEOMETRYCOLLECTION equivalent cavalcade.
$table->increments('id'); Machine-incrementing UNSIGNED INTEGER (primary cardinal) equivalent column.
$table->integer('votes'); INTEGER equivalent column.
$tabular array->ipAddress('visitor'); IP accost equivalent column.
$tabular array->json('options'); JSON equivalent cavalcade.
$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'); Motorcar-incrementing UNSIGNED MEDIUMINT (primary cardinal) equivalent cavalcade.
$table->mediumInteger('votes'); MEDIUMINT equivalent cavalcade.
$table->mediumText('description'); MEDIUMTEXT equivalent column.
$table->morphs('taggable'); Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR 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.
$tabular array->nullableTimestamps(); Alias of timestamps() method.
$table->indicate('position'); POINT equivalent column.
$table->polygon('positions'); POLYGON equivalent column.
$tabular array->rememberToken(); Adds a nullable remember_token VARCHAR(100) equivalent column.
$table->smallIncrements('id'); Auto-incrementing UNSIGNED SMALLINT (primary primal) equivalent column.
$tabular array->smallInteger('votes'); SMALLINT equivalent column.
$tabular array->softDeletes(); Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes.
$table->softDeletesTz(); Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes.
$tabular array->string('name', 100); VARCHAR equivalent cavalcade with a optional length.
$table->text('description'); TEXT equivalent column.
$table->time('sunrise'); Time equivalent cavalcade.
$table->timeTz('sunrise'); Fourth dimension (with timezone) equivalent column.
$tabular array->timestamp('added_on'); TIMESTAMP equivalent column.
$table->timestampTz('added_on'); TIMESTAMP (with timezone) equivalent column.
$table->timestamps(); Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
$table->timestampsTz(); Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
$table->tinyIncrements('id'); Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
$table->tinyInteger('votes'); TINYINT equivalent column.
$table->unsignedBigInteger('votes'); UNSIGNED BIGINT equivalent column.
$tabular array->unsignedDecimal('amount', 8, 2); UNSIGNED DECIMAL equivalent cavalcade with a precision (full digits) and calibration (decimal digits).
$tabular array->unsignedInteger('votes'); UNSIGNED INTEGER equivalent column.
$table->unsignedMediumInteger('votes'); UNSIGNED MEDIUMINT equivalent column.
$table->unsignedSmallInteger('votes'); UNSIGNED SMALLINT equivalent column.
$tabular array->unsignedTinyInteger('votes'); UNSIGNED TINYINT equivalent column.
$tabular array->uuid('id'); UUID equivalent cavalcade.
$tabular array->year('birth_year'); Year equivalent column.

Column Modifiers

In improver to the column types listed above, there are several cavalcade "modifiers" you may use while adding a column to a database table. For example, to make the cavalcade "nullable", you lot may use the nullable method:

                                              

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

$table -> string ( ' electronic mail ' ) -> nullable ();

});

Below is a list of all the available column modifiers. This list does non include the index modifiers:

Modifier Clarification
->after('cavalcade') Place the column "after" another column (MySQL)
->autoIncrement() Set INTEGER columns as motorcar-increment (principal key)
->charset('utf8') Specify a character set for the column (MySQL)
->collation('utf8_unicode_ci') Specify a collation for the column (MySQL/SQL Server)
->comment('my annotate') Add a comment to a cavalcade (MySQL)
->default($value) Specify a "default" value for the column
->first() Place the column "offset" in the tabular array (MySQL)
->nullable($value = true) Allows (by default) NULL values to be inserted into the column
->storedAs($expression) Create a stored generated cavalcade (MySQL)
->unsigned() Set INTEGER columns as UNSIGNED (MySQL)
->useCurrent() Prepare TIMESTAMP columns to use CURRENT_TIMESTAMP equally default value
->virtualAs($expression) Create a virtual generated column (MySQL)

Modifying Columns

Prerequisites

Earlier modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to brand the specified adjustments to the column:

                                              

composer require doctrine / dbal

Updating Cavalcade Attributes

The modify method allows y'all to modify some existing column types to a new type or modify the column'southward attributes. For case, you lot may wish to increase the size of a string column. To see the change method in activeness, let's increment the size of the proper noun cavalcade from 25 to fifty:

                                              

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

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

});

Nosotros could also change a column to exist nullable:

                                              

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

$table -> string ( ' name ' , l ) -> nullable () -> change ();

});

{note} Only the post-obit column types can be "changed": bigInteger, binary, boolean, engagement, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

Renaming Columns

To rename a column, y'all may use the renameColumn method on the Schema architect. Before renaming a cavalcade, be certain to add together the doctrine/dbal dependency to your composer.json file:

                                              

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

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

});

{note} Renaming whatever cavalcade in a tabular array that also has a column of type enum is non currently supported.

Dropping Columns

To drop a column, use the dropColumn method on the Schema builder. Before dropping columns from a SQLite database, you will demand to add the doctrine/dbal dependency to your composer.json file and run the composer update command in your terminal to install the library:

                                              

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

$table -> dropColumn ( ' votes ' );

});

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

                                              

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

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

});

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

Bachelor Command Aliases

Control Clarification
$table->dropRememberToken(); Driblet the remember_token column.
$tabular array->dropSoftDeletes(); Drib the deleted_at column.
$table->dropSoftDeletesTz(); Allonym of dropSoftDeletes() method.
$table->dropTimestamps(); Drib the created_at and updated_at columns.
$table->dropTimestampsTz(); Allonym of dropTimestamps() method.

Indexes

Creating Indexes

The schema architect supports several types of indexes. Start, permit'due south look at an example that specifies a column'south values should exist unique. To create the index, we tin can concatenation the unique method onto the column definition:

                                              

$table -> cord ( ' e-mail ' ) -> unique ();

Alternatively, y'all may create the index afterwards defining the column. For example:

                                              

$table -> unique ( ' email ' );

Yous may even pass an array of columns to an alphabetize method to create a compound (or composite) index:

                                              

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

Laravel will automatically generate a reasonable index proper noun, but you may pass a second argument to the method to specify the proper name yourself:

                                              

$table -> unique ( ' email ' , ' unique_email ' );

Available Index Types

Each index method accepts an optional second argument to specify the name of the index. If omitted, the proper noun volition be derived from the names of the table and column(southward).

Command Clarification
$table->main('id'); Adds a primary key.
$table->master(['id', 'parent_id']); Adds composite keys.
$table->unique('e-mail'); Adds a unique alphabetize.
$table->alphabetize('state'); Adds a plain index.
$tabular array->spatialIndex('location'); Adds a spatial alphabetize. (except SQLite)

Index Lengths & MySQL / MariaDB

Laravel uses the utf8mb4 grapheme set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the v.7.7 release or MariaDB older than the ten.two.two release, you may need to manually configure the default string length generated by migrations in guild for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider:

                                              

apply Illuminate\Support\Facades\ Schema ;

/**

* Bootstrap any awarding services.

*

* @render void

*/

public function boot ()

{

Schema :: defaultStringLength ( 191 );

}

Alternatively, you 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 choice.

Renaming Indexes

To rename an index, y'all may use the renameIndex method. This method accepts the electric current alphabetize name as its first argument and the desired name equally its second argument:

                                              

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

Dropping Indexes

To drop an alphabetize, you must specify the index's name. Past default, Laravel automatically assigns a reasonable name to the indexes. Concatenate the tabular array name, the name of the indexed column, and the alphabetize type. Hither are some examples:

Control Description
$table->dropPrimary('users_id_primary'); Drop a chief central from the "users" table.
$table->dropUnique('users_email_unique'); Driblet a unique index from the "users" tabular array.
$table->dropIndex('geo_state_index'); Driblet a basic index from the "geo" tabular array.
$tabular array->dropSpatialIndex('geo_location_spatialindex'); Drop a spatial index from the "geo" tabular array (except SQLite).

If yous pass an array of columns into a method that drops indexes, the conventional alphabetize name will be generated based on the tabular array name, columns and fundamental type:

                                              

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

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

});

Foreign Central Constraints

Laravel also provides back up for creating foreign cardinal constraints, which are used to force referential integrity at the database level. For instance, let'due south define a user_id column on the posts table that references the id column on a users table:

                                              

Schema :: tabular array ( ' posts ' , role ( Blueprint $tabular array ) {

$table -> unsignedInteger ( ' user_id ' );

$table -> strange ( ' user_id ' ) -> references ( ' id ' ) -> on ( ' users ' );

});

Yous may as well specify the desired action for the "on delete" and "on update" properties of the constraint:

                                              

$table -> foreign ( ' user_id ' )

-> references ( ' id ' ) -> on ( ' users ' )

-> onDelete ( ' cascade ' );

To driblet a strange key, you may utilize the dropForeign method. Strange central constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":

                                              

$table -> dropForeign ( ' posts_user_id_foreign ' );

Or, you may pass an array value which volition automatically use the conventional constraint proper name when dropping:

                                              

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

Yous may enable or disable foreign central constraints within your migrations by using the following methods:

                                              

Schema :: enableForeignKeyConstraints ();

Schema :: disableForeignKeyConstraints ();

How To Change Rails 5.1 Existing Id Column To Uuid,

Source: https://laravel.com/docs/5.6/migrations

Posted by: mcdanielmorly1947.blogspot.com

0 Response to "How To Change Rails 5.1 Existing Id Column To Uuid"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel