Skip to content

Instantly share code, notes, and snippets.

@pedzed
Created October 28, 2018 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedzed/30e15d9177d6f4b4f23e945d8d51106e to your computer and use it in GitHub Desktop.
Save pedzed/30e15d9177d6f4b4f23e945d8d51106e to your computer and use it in GitHub Desktop.
Laravel Foreign Keys Migration
<?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