How to add a column to an already existing table in Laravel using Migrations

First, you need to create the migration.
While creating the migration file we need to make sure the name gives us an idea of what is going on. For example,
if we are adding a column on the product table called product_price, we should first create a migration with the title

php artisan make:migration add_product_price_to_products_table --table=products

Doing this way, we will know why we created the migration and the migration will be created with its name beginning with the current date.

Then in the migration we add the table as required

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddColumnProductPriceToProducts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->string('product_price')->after('product_name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn('product_price');
        });
    }
}

Then we run the command.

php artisan migrate

If we want to migrate a specific file only then we can use the following command

php artisan migrate --path=database/migrations/filename.php

And the column will be added because of the up function. If we want to remove the column we use the down function.

If you want to roll back the migration using the following command.

php artisan migrate:rollback

If you want to roll back a specific migration file then you can use the following command.

php artisan migrate:rollback --path=database/migrations/filename.php


Here is an article on how a function helps in creating a slug in PHP and Laravel. Click here

2 thoughts on “How to add a column to an already existing table in Laravel using Migrations”

Leave a Comment

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

Tweet
Share
Share
Pin