Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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