diff --git a/src/Translators/Rules.php b/src/Translators/Rules.php index 81b2a036..fe77d191 100644 --- a/src/Translators/Rules.php +++ b/src/Translators/Rules.php @@ -37,8 +37,8 @@ public static function fromColumn(string $context, Column $column): array } if ($column->dataType() === 'id' && ($column->attributes() || Str::endsWith($column->name(), '_id'))) { - $reference = $column->attributes()[0] ?? Str::beforeLast($column->name(), '_id'); - $rules = array_merge($rules, ['integer', 'exists:' . Str::plural($reference) . ',id']); + $table = $column->modifiers()[0]['foreign'] ?? Str::plural($column->attributes()[0] ?? Str::beforeLast($column->name(), '_id')); + $rules = array_merge($rules, ['integer', 'exists:' . $table . ',id']); } if (in_array($column->dataType(), self::INTEGER_TYPES)) { diff --git a/tests/Feature/Translators/RulesTest.php b/tests/Feature/Translators/RulesTest.php index 80590543..46728071 100644 --- a/tests/Feature/Translators/RulesTest.php +++ b/tests/Feature/Translators/RulesTest.php @@ -128,6 +128,17 @@ public function forColumn_returns_exists_rule_for_foreign_keys($name, $table): v $this->assertContains("exists:{$table},id", $actual); } + #[Test] + public function forColumn_returns_exists_rule_for_foreign_keys_with_foreign_table_name(): void + { + $column = new Column('author_id', 'id', [['foreign' => 'users']]); + + $actual = Rules::fromColumn('context', $column); + + $this->assertContains('integer', $actual); + $this->assertContains('exists:users,id', $actual); + } + #[Test] public function forColumn_returns_gt0_rule_for_unsigned_numeric_types(): void {