Класс Blueprint
Класс Blueprint применяется внутри миграций для построения схемы таблицы. Экземпляр этого класса передаётся в метод Schema::create или Schema::table. Он предоставляет методы для определения колонок, индексов, внешних ключей и других ограничений.
Создание таблицы
Базовый синтаксис создания таблицы с помощью класса Blueprint:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->boolean('is_published')->default(false);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('posts');
}
};
?>
Изменение существующей таблицы
Для изменения структуры существующей таблицы используется метод Schema::table вместе с Blueprint:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->string('category')->nullable();
$table->integer('views')->default(0);
});
}
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn(['category', 'views']);
});
}
};
?>
Типы полей
Класс Blueprint предоставляет множество методов для создания полей различных типов:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name', 100);
$table->text('description')->nullable();
$table->decimal('price', 10, 2);
$table->integer('stock')->default(0);
$table->boolean('is_active')->default(true);
$table->date('release_date');
$table->json('attributes')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('products');
}
};
?>
Создание индексов
Для повышения производительности запросов можно добавлять индексы к полям с помощью методов index, unique и primary:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
$table->string('name');
$table->timestamps();
$table->index('name');
$table->index(['email', 'username']);
});
}
public function down(): void
{
Schema::dropIfExists('users');
}
};
?>
Внешние ключи
Метод foreign используется для создания внешних ключей, связывающих таблицы:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->onDelete('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->text('content');
$table->timestamps();
$table->index('post_id');
$table->index('user_id');
});
}
public function down(): void
{
Schema::dropIfExists('comments');
}
};
?>
Удаление колонок
Для удаления колонок используется метод dropColumn. Можно удалить как одну колонку, так и несколько:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('category');
$table->dropColumn(['views', 'is_published']);
});
}
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->string('category')->nullable();
$table->integer('views')->default(0);
$table->boolean('is_published')->default(false);
});
}
};
?>
Переименование колонок
Метод renameColumn позволяет изменить имя существующей колонки:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn('title', 'heading');
$table->renameColumn('body', 'content');
});
}
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn('heading', 'title');
$table->renameColumn('content', 'body');
});
}
};
?>