Getting started
Every example assumes a wired $schema, as built in
Installation.
Creating a table
create() takes a table name and a callback. The callback receives a Table
and describes what should exist.
use Dirthara\Schema\Table;
$schema->create('users', function (Table $table): void {
$table->id();
$table->string('email', 255)->unique();
$table->string('name')->nullable();
$table->boolean('active')->default(true);
$table->timestamps();
});
On PostgreSQL that compiles to:
CREATE TABLE "users" (
"id" BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"email" VARCHAR(255) NOT NULL,
"name" VARCHAR(255) NULL,
"active" BOOLEAN NOT NULL DEFAULT TRUE,
"created_at" TIMESTAMP NULL,
"updated_at" TIMESTAMP NULL,
CONSTRAINT "users_primary" PRIMARY KEY ("id"),
CONSTRAINT "users_email_unique" UNIQUE ("email")
)
The same definition on MySQL uses BIGINT … AUTO_INCREMENT, on SQLite
INTEGER PRIMARY KEY AUTOINCREMENT, and on SQL Server BIGINT IDENTITY(1,1).
You do not choose; the grammar for the connection's driver does.
Creating only when missing
$schema->createIfNotExists('users', function (Table $table): void {
$table->id();
$table->string('email', 255);
});
Changing a table
table() takes the same kind of callback. Anything you describe is a change to
apply, not a full picture of the table.
$schema->table('users', function (Table $table): void {
$table->string('phone', 40)->nullable();
$table->renameColumn('name', 'full_name');
$table->dropColumn('legacy_id');
});
An alter is not a diff. The package does not read the current table, so
$table->string('email') inside table() means "add this column", not "make
sure it looks like this". Use change() to modify a column that already
exists, described in Altering tables.
Asking, renaming and dropping
$schema->hasTable('users'); // bool
$schema->rename('users', 'people');
$schema->drop('people');
$schema->dropIfExists('people'); // no error when it is already gone
Choosing a connection
Every method takes an optional connection name as its last argument, and
using() returns a schema scoped to one connection.
$schema->create('reports', $definition, 'reporting');
$reporting = $schema->using('reporting');
$reporting->drop('stale_reports');