HomeLARAVELDifference between Schema::create() and Schema::table().

Difference between Schema::create() and Schema::table().

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.

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

FeatureSchema::create()Schema::table()
FunctionCreates a new tableModifies an existing table
Table existenceTable should not existTable must exist
Common useInitial migrationsUpdating table structure (add/drop/rename columns)
ExampleSchema::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.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *