2

I'm trying to migrate a specific line in one migration file.

Example:

Before:

Schema::create('categories', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('category_name');
  $table->integer('parent_id')->nullable();
  $table->timestamps();
});

After:

Schema::create('categories', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('category_name');
  $table->string('img_url'); // ← new column
  $table->integer('parent_id')->nullable();
  $table->timestamps();
});

And now I just want to migrate the line: $table->string('img_url');

Is it possible?

1
  • 1
    Doesn't work that way. If you want to add a column to an existing table, create a new migration and use Schema::table() instead of Schema::create(), then run php artisan migrate again. Commented Oct 21, 2019 at 16:51

1 Answer 1

5

It sounds like you are trying to add a column to a table that has already been created via migration. If that is the case, rather than using Schema::create(...), you need to use Schema::table(...).

Typically, you would create a new migration for this:

$ php artisan make:migration add_img_url_to_categories

Which will create a new file at /database/migrations called something like 2019_10_21_165554_add_img_url_to_categories.php. Then add this code to the up() function:

public function up()
{
  Schema::table('categories', function (Blueprint $table) {
    $table->string('img_url');
  });
}

Another option you have is to edit the migration exactly as you have done (per the code in your question), and then run:

$ php artisan migrate:fresh // drop all tables and re-run all migrations

or

$ php artisan migrate:refresh // reset and re-run all migrations

But keep in mind that these are both destructive operations – meaning you will lose any data you already have in your database. In early development, that might not matter. But you should really establish the habit of creating new migrations for database changes, rather than editing existing migrations.

The purpose of migrations is so that you (or anyone using your app) can quickly deploy a database that matches the schema your app is expecting. During development, it is not uncommon to edit your migrations as you tweak your database schema to accommodate the features you are developing.

However, once you have deployed or published your app, you should consider all of the migrations to be locked or read-only. Any database changes from that point should be done in a new migration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.