Skip to content

Instantly share code, notes, and snippets.

@cabloo
Last active May 14, 2016 18:24
Show Gist options
  • Save cabloo/5f58a80af5deb36c55728aaa69ef54bd to your computer and use it in GitHub Desktop.
Save cabloo/5f58a80af5deb36c55728aaa69ef54bd to your computer and use it in GitHub Desktop.
Laravel Drop Foreign Column
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
use Illuminate\Database\Migrations\Migration;
class CreateSomeRelation extends Migration
{
/**
* @var Builder
*/
protected $schema;
public function __construct()
{
$this->schema = get_schema();
}
public function up()
{
$this->schema->table('some_table', function (Blueprint $table) {
$table->integer('some_col')->unsigned();
$table->foreign('some_col')->references('id')->on('some_table');
});
}
public function down()
{
$this->schema->table('some_table', function (Blueprint $table) {
$table->dropForeignColumn('some_col');
// vs.
// $table->dropForeign('some_table_some_col_foreign');
// $table->dropColumn('some_col');
});
}
}
<?php
// Place the following in bootstrap/app.php before return $app;
use App\Support\Database\Blueprint;
use App\Support\Database\MySqlGrammar;
use Illuminate\Database\Schema\Builder;
/**
* @return Builder
*/
function get_schema()
{
DB::setSchemaGrammar(new MySqlGrammar());
$schema = DB::getSchemaBuilder();
$schema->blueprintResolver(function ($table, $callback) {
return new Blueprint($table, $callback);
});
return $schema;
}
<?php
namespace App\Support\Database;
class Blueprint extends \Illuminate\Database\Schema\Blueprint
{
public function dropForeignColumn($column)
{
$this->dropForeign($this->table.'_'.$column.'_foreign');
$this->dropColumn($column);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment