laravel

How to Add a New Column to Existing Table in a Migration

Problem

I have been having nightmares not being able to add a new column to my users table. Can’t seem to figure it out.

I tried to edit the migration file using…

<?php
public function up()
{
    Schema::create('users', function ($table) {
        $table->integer("paid");
    });
}

In terminal, I execute php artisan migrate:install and migrate.

How do I add new columns?

Solution

You cannot update any migrations that have been migrated already. If it is added to the migrations table already, it wont process it again. Your solution is to create a new migration, for which you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models

for Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

You will be using the Schema::table() method (since you’re accessing the existing table, and not creating a new one). And you can add a column like this:

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}

and don’t forget to add the rollback option:

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('paid');
    });
}

Then you can run your migrations:

php artisan migrate

And for Laravel 5:

Edit:

use $table->integer('paid')->after('any_column'); to add this field after specific column.

About the author

Avatar

laravelrecipies