Use Schema::hasTable() and Schema::hasColumn() to write safe, defensive migrations and dynamic installer scripts.
When writing data migrations across environments, package installers, or multi-tenant database upgrades, attempting to alter a table or column that does not exist throws database exceptions.
The Schema facade provides helper methods to inspect database structure before running modifications.
Checking Table and Column Existence in Migrations
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Modify table only if it exists
if (Schema::hasTable('orders')) {
Schema::table('orders', function (Blueprint $table) {
// Add column only if it hasn't been added yet
if (! Schema::hasColumn('orders', 'tracking_number')) {
$table->string('tracking_number')->nullable()->after('status');
}
});
}
}
public function down(): void
{
if (Schema::hasTable('orders') && Schema::hasColumn('orders', 'tracking_number')) {
Schema::table('orders', function (Blueprint $table) {
$table->dropColumn('tracking_number');
});
}
}
};
Checking Multiple Columns Simultaneously
Pass an array to Schema::hasColumns() to verify multiple columns exist:
if (Schema::hasColumns('users', ['email', 'phone', 'billing_address'])) {
// All specified columns exist in the table
}
Summary
- Prevents
Table already existsorColumn not founderrors during dynamic schema operations. Schema::hasTable('table')inspects table existence.Schema::hasColumn('table', 'column')andSchema::hasColumns('table', [...])inspect column definitions.
Related Tips
View all tips →Use Database Expressions for Dynamic Migration Defaults
Pass an Expression instance to Laravel's migration default() method to define raw SQL functions, dynamic timestamps, and calculated defaults directly in your database schema.
Index Dynamic JSON Attributes with Generated Virtual Columns
Use virtualAs() and storedAs() in migrations to create generated database columns for high-speed indexing on JSON attributes.