Creating and running migrations — artisan make:migration, migrate
Concept
Schema::create(), Schema::table(), Schema::drop(), and Schema::dropIfExists() are the main Schema facade methods for managing tables.
Schema::create(string $table, Closure $callback): Creates a new table. The closure receives a Blueprint which you use to define columns and constraints.
Schema::table(string $table, Closure $callback): Modifies an existing table — adding columns, dropping columns, renaming columns, adding indexes.
Schema::drop(string $table): Drops the table. Throws an exception if the table doesn't exist.
Schema::dropIfExists(string $table): Drops the table only if it exists. Always use this in down() methods.
Schema::hasTable(string $table) / Schema::hasColumn(string $table, string $column): Check existence. Useful in conditional migrations or seeders.
Schema::rename(string $from, string $to): Rename a table.
Schema::disableForeignKeyConstraints() / Schema::enableForeignKeyConstraints(): Temporarily disable FK checks — needed before dropping tables that are referenced by foreign keys. Used in migrate:fresh and test refresh cycles.
Schema::connection(string $name): Run schema operations on a specific connection: Schema::connection('analytics')->create(...).
Code Example
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Creating a new table
return new class extends Migration
{
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->decimal('price', 10, 2);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('products');
}
};
// Modifying an existing table (separate migration)
return new class extends Migration
{
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->string('sku', 50)->unique()->after('id'); // add column
$table->unsignedInteger('stock')->default(0)->after('price'); // add column
$table->index('name'); // add index
});
}
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn(['sku', 'stock']);
$table->dropIndex(['name']);
});
}
};
// Rename table
Schema::rename('old_table_name', 'new_table_name');
// Conditional operations
if (!Schema::hasTable('cache')) {
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration');
});
}
if (!Schema::hasColumn('users', 'timezone')) {
Schema::table('users', function (Blueprint $table) {
$table->string('timezone', 50)->nullable()->after('email');
});
}