Изменение существующих таблиц
Когда таблица уже создана, а нужно добавить колонку, изменить тип или удалить поле — создаётся новая миграция с методом Schema::table.
Создание
php artisan make:migration add_status_to_posts_table --table=posts
Флаг --table=posts создаёт заготовку с Schema::table.
Добавление колонки
public function up(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->string('status')->default('draft')->after('title');
});
}
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('status');
});
}
Удаление колонки
$table->dropColumn('status');
$table->dropColumn(['status', 'views']);
Переименование колонки
$table->renameColumn('title', 'name');
На старых версиях MySQL требуется пакет doctrine/dbal.
Изменение типа
$table->string('title', 500)->change();
$table->integer('views')->nullable()->change();
Метод change() требует полного переопределения колонки со всеми модификаторами.
Изменение нескольких колонок
В одном замыкании можно делать всё сразу:
Schema::table('posts', function (Blueprint $table) {
$table->string('slug')->unique()->after('title');
$table->boolean('published')->default(false);
$table->timestamp('published_at')->nullable();
});
Индексы
$table->index('status');
$table->unique('slug');
$table->fullText('body');
$table->dropIndex(['status']);
$table->dropUnique(['slug']);
Переименование таблицы
Schema::rename('posts', 'articles');
Безопасное удаление
Если колонка может не существовать:
if (Schema::hasColumn('posts', 'status')) {
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('status');
});
}
Написание down
Метод down должен точно откатывать то, что сделал up. Если добавил колонку — удали. Если переименовал — верни имя. Это важно для миграции:refresh.