Created
October 31, 2023 14:56
-
-
Save MrPunyapal/40388eb5356363c7a189969263064853 to your computer and use it in GitHub Desktop.
Laravel Database Schema Migration with Multiple Tables
This file contains 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 | |
public function up(): void | |
{ | |
// Method 1: Adding 'team_id' Foreign Key to Different Tables One by One | |
Schema::table('users', function (Blueprint $table) { | |
$table->foreignIdFor(Team::class)->nullable(); | |
}); | |
Schema::table('posts', function (Blueprint $table) { | |
$table->foreignIdFor(Team::class)->nullable(); | |
}); | |
Schema::table('comments', function (Blueprint $table) { | |
$table->foreignIdFor(Team::class)->nullable(); | |
}); | |
// Method 2: Adding 'team_id' Foreign Key to Different Tables Using a foreach Loop | |
foreach (['users', 'posts', 'comments', 'another_table'] as $table) { | |
// ⚙️ Adding 'team_id' foreign key using foreignIdFor method | |
Schema::table($table, function (Blueprint $table) { | |
$table->foreignIdFor(Team::class)->nullable(); | |
}); | |
} | |
// Laravel devs, which method do you prefer for adding 'team_id' foreign keys to | |
// different tables: Method 1 or Method 2? | |
// Let us know! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment