Created
October 28, 2018 16:35
-
-
Save pedzed/30e15d9177d6f4b4f23e945d8d51106e to your computer and use it in GitHub Desktop.
Laravel Foreign Keys Migration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Facades\Schema; | |
use Illuminate\Database\Schema\Blueprint; | |
use Illuminate\Database\Migrations\Migration; | |
class CreateForeignKeys extends Migration | |
{ | |
/** | |
* A list of foreign keys. | |
* | |
* @var array | |
*/ | |
private $tablesWithForeignKeys = [ | |
'employees' => [ | |
[ | |
'column' => 'role_id', | |
'references' => 'id', | |
'on' => 'roles', | |
], | |
// ... | |
], | |
// ... | |
]; | |
/** | |
* Run the migrations. | |
* | |
* @return void | |
*/ | |
public function up() | |
{ | |
foreach ($this->tablesWithForeignKeys as $table => $foreignKeys) { | |
$this->createForeignKeysForTable($foreignKeys, $table); | |
} | |
} | |
private function createForeignKeysForTable(array $foreignKeys, string $table) | |
{ | |
Schema::table($table, function (Blueprint $table) use ($foreignKeys) { | |
foreach ($foreignKeys as $foreignKey) { | |
$table->foreign($foreignKey['column']) | |
->references($foreignKey['references']) | |
->on($foreignKey['on']) | |
; | |
} | |
}); | |
} | |
/** | |
* Reverse the migrations. | |
* | |
* @return void | |
*/ | |
public function down() | |
{ | |
foreach ($this->tablesWithForeignKeys as $table => $foreignKeys) { | |
$this->dropForeignKeysForTable($foreignKeys, $table); | |
} | |
} | |
private function dropForeignKeysForTable(array $foreignKeys, string $table) | |
{ | |
foreach ($foreignKeys as $foreignKey) { | |
$column = $foreignKey['column']; | |
// Example foreign key: employees_role_id_foreign | |
Schema::dropForeign("{$table}_{$column}_foreign"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment