Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Created October 31, 2023 14:56
Show Gist options
  • Save MrPunyapal/40388eb5356363c7a189969263064853 to your computer and use it in GitHub Desktop.
Save MrPunyapal/40388eb5356363c7a189969263064853 to your computer and use it in GitHub Desktop.
Laravel Database Schema Migration with Multiple Tables
<?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