onsa
12/19/2016 - 4:12 PM

Sample usage of Laravel Migration

Sample usage of Laravel Migration

<?php

/*
 *  php artisan migrate runs a migration
 *  php artisan migrate:rollback rolls back a migration
 *  php artisan migrate:reset rolls back all migrations
 *  php artisan migrate:refresh rolls back and executes again all migrations
 */

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

class CreateUsersTable extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		// override the default connection
		Schema::connection('alernative_connection')->

		// create table
		Schema::create('users', function (Blueprint $table) {
			// define the engine
			$table->engine = 'InnoDB';
				->increments('id');
					->nullable();
				->bigIncrements('id');
					->primary();
				->integer('votes');
					->unsigned();
				->bigInteger('votes');
					// position in MySQL DBs
				  ->after('email');
				->mediumInteger('votes');
				->smallInteger('votes');
				->tinyInteger('numbers');
				->boolean('confirmed');
				->char('name', 4);
				->date('created_at');
				->dateTime('created_at');
				// precision, scale
				->decimal('amount', 5, 2);
				->double('column', 15, 8);
				->enum('gender', array('male', 'female'));
				->float('amount');
				// INTEGER taggable_id & STRING taggable_type
				->morphs('taggable');
				// VARCHAR(100) password reminder
				->rememberToken();
				->softDeletes();
				->dropSoftDeletes();
				->strings('name', 100);
					->unique();
				->text('quality');
					->default('excellent');
				->longText('description');
				->mediumText('description');
				->time('sunrise');
				->timestamp('added_on');
				// created_at & updated_at
				->timestamps();
				->dropTimestamps();
				->nullableTimestamps();
				->string('user_name', 60);
				->integer('team_id')->unsigned()->index();

				->foreign('team_id')->references('id')->on('teams');
					// change foreign table upon deletion/update
					->onDelete('cascade');
					->onUpdate('cascade');
				->dropForeign('posts_user_id_foreign');
				// composite key
				->primary(array('first_name', 'last_name'));
				->dropPrimary('users_id_primary');
				->unique('email');
				->dropUnique('email');
				// index
				->index('state');
				->dropIndex('state');
				->timestamps();
				->softDeletes();
		});

		// rename table
		Schema::rename($from, $to);

		// rename column
		Schema::table('users', function($table) {
			$table->renameColumn($oldName, $newName);
				->dropColumn(array('votes', 'avatar', 'location'));
		});

		// boolean to check existence of table
		Schema::hasTable('users');
		// boolean to check existence  of column on table
		Schema::hasColumn('users', 'email');

	}

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