Igor Simic
4 years ago

Laravel migration - change default value of column


If you already created table with some specific field using Laravel migration, and now you want to update that table and set specific defaut value for a field - here is how to do it.

In our case we already have a database table called photos and inside of this table we want to add new field called order.
First let's create migration using terminal and artisan:
php artisan make:migration edit_photos_add_order

This command will create new migration file in database/migrations folder. Open that file and add code which will create this new field:
<?php

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

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

            $table->integer('order')->after('id');
        });
    }

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

            $table->dropColumn('order');

        });
    }
}

Now we will run artisan command to execute this migration and actually create that field
php artisan migrate

Field is created, but let's pretend that  we forgot to set the default value for it. Now we can either rollback migration 
php artisan migrate:rollback --step=1
and update the code, or just create new migration which will update the already existing field. In our case we are going to do second option - create new migration.

Create new migration file:
php artisan make:migration edit_photos_set_order_default_value
This will create new migration file, open it and add code which will set default value of 0 and update field using method change
public function up()
{
    Schema::table('post_photos', function (Blueprint $table) {

        $table->integer('order')->default(0)->change();
    });
}
If we roll back this migration, we need to remove default value from that field using migration and this is how to do it:
 Schema::table('photos', function (Blueprint $table) {

    $table->integer('order')->default(NULL)->change();
});

And that would be it, now you know how to easily update database table fields using laravel migration to set a default value for specific column.