Agregar una nueva columna a una tabla existente en una migración


Realmente no puedo averiguar cómo agregar una nueva columna a mi tabla de salida en mi base de datos usando PHP laravel framework.

He intentado editar el archivo de migración a

 public function up()
{
    Schema::create('users', function($table){

         $table->integer("paid");


    });
}

Y en terminal php artisan migrate:install y migrate

Cómo agregar nuevas columnas?

Author: Peter verleg, 2013-05-28

8 answers

Para crear una migración, puede usar el comando migrate:make en la CLI Artisan. Use un nombre específico para evitar chocar con los modelos existentes

Para Laravel 3:

php artisan migrate:make add_paid_to_users

Para Laravel 5+:

php artisan make:migration add_paid_to_users

Luego debe usar el método Schema::table() (ya que está accediendo a una tabla existente, no creando una nueva). Y puedes agregar una columna como esta:

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}

Y no olvides agregar la opción de reversión:

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('paid');
    });
}

Entonces usted puede ejecutar su migraciones:

php artisan migrate

Todo esto está bien cubierto en la documentación para ambos Laravel 3:

Y para Laravel 4 / Laravel 5:

Editar:

Use $table->integer('paid')->after(whichever_column); para agregar este campo después de una columna específica.

 337
Author: Phill Sparks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-24 11:52:24

Añadiré a la respuesta de mike3875 para futuros lectores usando Laravel 5.1 y en adelante.

Para hacer las cosas más rápidas, puedes usar la bandera "table table" así:

php artisan make:migration add_paid_to_users --table="users"

Esto agregará el contenido del método up y down automáticamente:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        //
    });
}

De manera similar, puede usar la opción --create["table_name"] al crear nuevas migraciones que agregarán más repeticiones a sus migraciones. Pequeño punto, pero útil cuando se hace un montón de ellos!

 40
Author: camelCase,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-12 14:29:50

Si estás usando Laravel 5, el comando sería;

php artisan make:migration add_paid_to_users

Todos los comandos para hacer cosas (controladores, modelos, migraciones, etc.) se han movido bajo el comando make:.

php artisan migrate sigue siendo el mismo sin embargo.

 24
Author: mikelovelyuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-09 11:38:57

Puede agregar nuevas columnas dentro del método Schema::create inicial de la siguiente manera:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

Si ya ha creado una tabla, puede agregar columnas adicionales a esa tabla creando una nueva migración y utilizando el método Schema::table:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

La documentación es bastante completa sobre esto, y no ha cambiado demasiado de versión 3 a versión 4.

 14
Author: tplaner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-28 12:26:44

Simplemente puede modificar su archivo de migración existente, por ejemplo, agregando una columna en su tabla, y luego en su terminal escribiendo:

$ php artisan migrate:refresh
 8
Author: Mahana Delacour,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-17 14:01:42

Laravel 5.6

En caso de que desee agregar una nueva columna como CLAVE FORÁNEA a una tabla existente.

Cree una nueva migración ejecutando este comando: make: migration

Ejemplo :

php artisan make:migration add_store_id_to_users_table --table=users

En la carpeta database/migrations tiene un nuevo archivo de migración, algo así como:

2018_08_08_093431_add_store_id_to_users_table.php (ver los comentarios)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddStoreIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            // You probably want to make the new column nullable
            $table->integer('store_id')->unsigned()->nullable()->after('password');

            // 2. Create foreign key constraints
            $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Drop foreign key constraints
            $table->dropForeign(['store_id']);

            // 2. Drop the column
            $table->dropColumn('store_id');
        });
    }
}

Después de eso ejecute el comando :

php artisan migrate

En caso de que desee deshacer la última migración por cualquier motivo, ejecute este comando :

php artisan migrate:rollback

Puede encontrar más información sobre las migraciones en los documentos

 3
Author: chebaby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-08 10:34:58

Esto se trabaja en laravel 5.1.

Primero, en tu terminal ejecuta este código

php artisan make:migration add_paid_to_users --table=users

Después de eso, vaya al directorio de su proyecto y expanda directory database - migration y edite el archivo add_paid_to_users.php, añade este código

public function up()
{
    Schema::table('users', function (Blueprint $table) {
         $table->string('paid'); //just add this line
    });
}

Después de eso vuelve a tu terminal y ejecuta este comando

php artisan migrate

Espero que esto ayude.

 2
Author: Rosidin Bima,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-27 11:26:29

Primero revierta su migración anterior

php artisan migrate:rollback

Después de eso, puede modificar su archivo de migración existente (agregar nuevas , renombrar o eliminar columnas) y luego Volver a ejecutar su archivo de migración

php artisan migrate
 0
Author: noobgrammer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-26 06:52:24