laravel migration – Add column in database table

laravel migration – Add column in database table



To add column in existing table we need to follow below given steps one by one.





Step 1

Create migration file, You can name it as you like adding_user_ip_address_users_table. Check example.



php artisan make:migration add_user_ip_address_to_users_table --table=users

This will create a file under “Your Projects/database/migrations” with name similar to “adding_user_ip_address_users_table”. Open this file with any text editor, You should see something like this





<?php

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

class AddingUserIpAddressUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }

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

Step 2

Now its time we add field in up function



 public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            // Adding Field in database
            $table->string('user_ip')->nullable()
            ->after('name');
        });
    }

Here we are adding “user_ip” field as string. String because ip address includes dots and numbers.





We also need to add a line in down function as well something like this.



public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            // Drop the column
            $table->dropColumn('user_ip');
        });
    }

Step 3

Now our file should look something like this and we need to run migration command.





<?php

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

class AddingUserIpAddressUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            // Adding Field in database
            $table->string('user_ip')->nullable()->after('name');
        });
    }

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

Run migration command



php artisan migrate

And we should have new column in our database.





if for some reason you want to undo the changes then run this command



php artisan migrate:rollback

Hope this helps