Snippets

Josh Graham Abstracting migrations

Created by Josh Graham
<?php

namespace App\Library\Classes\Database;

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

/**
 *
 * @var TABLE_NAME Declare `const TABLE_NAME='your_table';` in extending class.
 *
 */
abstract class Migration extends Migrations\Migration {
    public $TABLE_NAME;

    public function __construct()
    {
        $this->TABLE_NAME = static::TABLE_NAME;
    }

    public function hasColumn(string $columnName) {
        return Schema::hasColumn($this->TABLE_NAME, $columnName);
    }

    public function table(callable $f) {
        return Schema::table($this->TABLE_NAME, $f);
    }
}
<?php

use App\Library\Classes\Database\Migration;
use Illuminate\Database\Schema\Blueprint;

class AddTemplateUrlColumnToEmailLogsTable extends Migration {

    const TABLE_NAME = 'email_logs';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        // Add new `template_url` column if if doesn't exist
        if (!$this->hasColumn('template_url')) {
            $this->table(function (Blueprint $table) {
                $table->string('template_url', 256)->after('content')->nullable();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        // Remove the new column if it exists
        if ($this->hasColumn('template_url')) {
            $this->table(function (Blueprint $table) {
                $table->dropColumn('template_url');
            });
        }
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.