How to Add New Column to Table – Laravel

Laravel migration is a way that makes you to create a table in your database without a database manager.

A migration class has two methods: up and down. The up method useful to add new column, tables, and even indexes to a database, while the down performs the reverse the operations of those by the up method.

We need to use the Schema::table() method when accessing an existing table to add a new column to the table.

<?php
    public function up()
    {
        Schema::table('customers', function (Blueprint $table) {

            // 1. Create new column
            // You probably want to make the new column nullable
            $table->integer('store_id')->unsigned()->nullable()->after('password');

            // 2. Create foreign key constraints
            $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
        });
    }

As shown above, up() function uses the  Schema::table() method to refer to the ‘customers’ table. You can pass functions to the table using the $table variable.

It then adds the new field of ‘store_id’ to ‘customers’ table and passes it the attributes to be nullable. The after('password') method helps define the location this new column will come up. In this case, it comes after the password field (column).

You can also create foreign key constraints for the new added field. As shown in the code snipper above, you may link the ‘store_id’ to ‘id’ in the ‘stores’ table. It can be set null on deletes.

Laravel allows us to set up entire database operations in the migration file. However it is often recommended to add a rollback option that helps drop the new column if required.

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

Leave a Comment