DEV Community

Pradeep Kumar
Pradeep Kumar

Posted on

1 1

Error Free Laravel Migrations

If you're trying to modify database table, use following code for migrations:

<?php

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

class [class_name] extends Migration
{

    public function table()
    {
        return '[table_name]';
    }

    public function columns()
    {
        return [
            [
                "type"=>"integer",
                "column"=>"[column_name]",
                "after"=>"[after_column_name] (optional)",
            ]
        ];
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        $table = $this->table();
        $list = $this->columns();

        foreach ($list as $item)
        {
            if(!Schema::hasColumn($table, $item['column'])){
                Schema::table($table, function (Blueprint $table) use ($item)
                {
                    $type = $item['type'];
                    $column = $item['column'];
                    if(isset($item['after']))
                    {
                        $table->$type($column)->nullable()->after($item['after']);
                    } else
                    {
                        $table->$type($column)->nullable();
                    }
                });
            }
        }

    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        $table = $this->table();
        $list = $this->columns();
        foreach ($list as $item)
        {
            if(Schema::hasColumn($table, $item['column'])){
                Schema::table($table, function (Blueprint $table) use ($item)
                {
                    $column = $item['column'];
                    $table->dropColumn($column);
                });
            }
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more