In Laravel, Schema::create() and Schema::table() are both used for database migrations, but they serve different purposes. Let’s break it down carefully:
1. Schema::create()
- Purpose: To create a new table in the database.
- Usage: Used when the table does not exist yet.
- Syntax Example:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
- What it does:
- Creates a table called
users - Adds the specified columns
- Sets up primary keys, unique constraints, etc.
- Creates a table called
2. Schema::table()
- Purpose: To modify an existing table.
- Usage: Used for adding, dropping, or altering columns or indexes in an existing table.
- Syntax Example:
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable(); // Add new column
$table->dropColumn('email'); // Remove column
});
- What it does:
- Changes the structure of an existing table
- You cannot use it to create a new table
- Common modifications: add/drop columns, rename columns, add/drop indexes
✅ Key Differences
| Feature | Schema::create() | Schema::table() |
|---|---|---|
| Function | Creates a new table | Modifies an existing table |
| Table existence | Table should not exist | Table must exist |
| Common use | Initial migrations | Updating table structure (add/drop/rename columns) |
| Example | Schema::create('users', ...) | Schema::table('users', ...) |
💡 Tip:
- Use
Schema::create()in the initial migration for a table. - Use
Schema::table()for future migrations that change the table structure.
