PHP code example of jorgemddev / kumbiaphp-migrations

1. Go to this page and download the library: Download jorgemddev/kumbiaphp-migrations library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jorgemddev / kumbiaphp-migrations example snippets



return [
    'development' => [
        'type'     => 'mysql',       // mysql | pgsql | sqlite
        'host'     => 'localhost',
        'name'     => 'mi_base',
        'username' => 'root',
        'password' => '',
        'charset'  => 'utf8mb4',     // opcional, por defecto utf8mb4
        'port'     => 3306,          // opcional
    ],
    'production' => [
        'type'     => 'mysql',
        'host'     => 'db.servidor.com',
        'name'     => 'mi_base_prod',
        'username' => 'usuario',
        'password' => 'secreto',
    ],
];



class CreateProductsTable extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('sku', 100)->unique();
            $table->decimal('price', 10, 2);
            $table->integer('stock')->default(0);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}



class AddDescriptionToProductsTable extends Migration
{
    public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->text('description')->nullable()->after('name');
            $table->string('image')->nullable();
        });
    }

    public function down()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn(['description', 'image']);
        });
    }
}



class FixScheduleExemptDefault extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('schedule_exempt')->default(false)->change();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('schedule_exempt')->change();
        });
    }
}



class CreateOrdersTable extends Migration
{
    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->enum('status', ['pending', 'paid', 'cancelled'])->default('pending');
            $table->decimal('total', 10, 2);
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('orders');
    }
}

$table->string('email')->unique()->nullable(false);
$table->integer('views')->default(0)->unsigned();
$table->string('bio')->nullable()->after('email');
$table->timestamp('verified_at')->nullable()->useCurrent();
$table->string('slug')->index();
$table->boolean('active')->change();

// Definición completa
$table->foreign('category_id')
      ->references('id')
      ->on('categories')
      ->onDelete('cascade')   // CASCADE | RESTRICT | SET NULL | NO ACTION
      ->onUpdate('restrict');

// Métodos abreviados
$table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
$table->foreign('role_id')->references('id')->on('roles')->restrictOnDelete();
$table->foreign('parent_id')->references('id')->on('categories')->nullOnDelete();

// Eliminar clave foránea
$table->dropForeign('user_id_foreign');

// En la definición de columna
$table->string('email')->unique();
$table->string('slug')->index();

// Como comando independiente
$table->unique(['email', 'tenant_id'], 'unique_email_per_tenant');
$table->index(['last_name', 'first_name']);
$table->primary(['id', 'type']);

// Eliminar índices
$table->dropUnique('unique_email_per_tenant');
$table->dropIndex('products_name_index');
$table->dropPrimary();

// Verificar existencia
if (!Schema::hasTable('products')) { ... }
if (!Schema::hasColumn('products', 'price')) { ... }

// Renombrar tabla
Schema::rename('old_name', 'new_name');

// Eliminar tabla
Schema::drop('products');
Schema::dropIfExists('products');

// Deshabilitar claves foráneas temporalmente
Schema::withoutForeignKeyConstraints(function () {
    Schema::drop('users');
});

$tables = Schema::getTables();
// ['categories', 'migrations', 'orders', 'products', 'users']

$columns = Schema::getColumns('products');

// Ejemplo de resultado
[
    ['name' => 'id',    'type' => 'bigint unsigned', 'nullable' => false, 'default' => null, 'key' => 'PRI', 'extra' => 'auto_increment', 'comment' => null],
    ['name' => 'name',  'type' => 'varchar(255)',    'nullable' => false, 'default' => null, 'key' => null,  'extra' => null,             'comment' => null],
    ['name' => 'price', 'type' => 'decimal(10,2)',   'nullable' => false, 'default' => null, 'key' => null,  'extra' => null,             'comment' => null],
]

$indexes = Schema::getIndexes('products');

// Ejemplo de resultado
[
    ['name' => 'PRIMARY',           'columns' => ['id'],  'unique' => true,  'primary' => true],
    ['name' => 'products_sku_unique', 'columns' => ['sku'], 'unique' => true,  'primary' => false],
    ['name' => 'products_name_index', 'columns' => ['name'],'unique' => false, 'primary' => false],
]

$fks = Schema::getForeignKeys('orders');

// Ejemplo de resultado
[
    [
        'name'       => 'orders_user_id_foreign',
        'columns'    => ['user_id'],
        'on_table'   => 'users',
        'references' => ['id'],
        'on_delete'  => 'CASCADE',
        'on_update'  => 'RESTRICT',
    ],
]

Schema::connection('production');

$tables = Schema::getTables();
$cols   = Schema::getColumns('users');
$fks    = Schema::getForeignKeys('orders');


// app/database/seeds/UsersSeeder.php

class UsersSeeder extends Seeder
{
    public function run()
    {
        $this->insert('users', [
            [
                'name'       => 'Administrador',
                'email'      => '[email protected]',
                'password'   => password_hash('secret', PASSWORD_DEFAULT),
                'is_active'  => 1,
                'created_at' => date('Y-m-d H:i:s'),
            ],
        ]);
    }
}


// app/database/seeds/DatabaseSeeder.php

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call([
            UsersSeeder::class,
            CategoriesSeeder::class,
            ProductsSeeder::class,
        ]);
    }
}

// Insertar filas
$this->insert('tabla', $filas);

// Vaciar tabla
$this->truncate('tabla');

// SQL personalizado
$this->query('UPDATE config SET value = ? WHERE key = ?', ['activo', 'status']);

// Llamar a otro seeder
$this->call(OtroSeeder::class);
$this->call([SeederA::class, SeederB::class]);
bash
php app/bin/migrate --install
bash
php app/bin/migrate --install
bash
# Ejecutar migraciones pendientes
php app/bin/migrate

# Ver estado de todas las migraciones
php app/bin/migrate --status

# Revertir el último lote de migraciones
php app/bin/migrate --rollback

# Revertir todas las migraciones
php app/bin/migrate --reset

# Revertir todo y volver a ejecutar
php app/bin/migrate --refresh

# Crear la tabla de control (solo la primera vez)
php app/bin/migrate --install

# Ayuda
php app/bin/migrate --help
bash
# Migración en blanco
php app/bin/migrate make:migration nombre_descriptivo

# Para crear una tabla nueva
php app/bin/migrate make:migration create_products_table --create=products

# Para modificar una tabla existente
php app/bin/migrate make:migration add_price_to_products --table=products
bash
# Ejecutar DatabaseSeeder
php app/bin/seed

# Ejecutar un seeder específico
php app/bin/seed --class=UsersSeeder
bash
# 1. Crear la migración
php app/bin/migrate make:migration create_orders_table --create=orders

# 2. Editar app/migrations/YYYY_MM_DD_HHMMSS_create_orders_table.php

# 3. Aplicar
php app/bin/migrate

# 4. Si hay un error, revertir, corregir y volver a aplicar
php app/bin/migrate --rollback
php app/bin/migrate

# 5. Versionar
git add app/migrations/
git commit -m "feat: add orders table"
bash
git pull origin main
php app/bin/migrate

src/
├── Grammar/
│   ├── Grammar.php
│   ├── MySqlGrammar.php
│   ├── PostgresGrammar.php
│   └── SQLiteGrammar.php
├── Migration.php
├── MigrationCreator.php
├── MigrationDatabase.php
├── MigrationRepository.php
├── Migrator.php
├── Blueprint.php
├── ColumnDefinition.php
├── ForeignKeyDefinition.php
├── Schema.php
└── Seeder.php