Skip to content

Commit e4a7397

Browse files
authored
Fix exists rule when using foreign reference (#722)
1 parent 2a743d5 commit e4a7397

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/Translators/Rules.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ public static function fromColumn(string $context, Column $column): array
3737
}
3838

3939
if ($column->dataType() === 'id' && ($column->attributes() || Str::endsWith($column->name(), '_id'))) {
40-
$reference = $column->attributes()[0] ?? Str::beforeLast($column->name(), '_id');
41-
$rules = array_merge($rules, ['integer', 'exists:' . Str::plural($reference) . ',id']);
40+
$table = $column->modifiers()[0]['foreign'] ?? Str::plural($column->attributes()[0] ?? Str::beforeLast($column->name(), '_id'));
41+
$rules = array_merge($rules, ['integer', 'exists:' . $table . ',id']);
4242
}
4343

4444
if (in_array($column->dataType(), self::INTEGER_TYPES)) {

tests/Feature/Translators/RulesTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,17 @@ public function forColumn_returns_exists_rule_for_foreign_keys($name, $table): v
128128
$this->assertContains("exists:{$table},id", $actual);
129129
}
130130

131+
#[Test]
132+
public function forColumn_returns_exists_rule_for_foreign_keys_with_foreign_table_name(): void
133+
{
134+
$column = new Column('author_id', 'id', [['foreign' => 'users']]);
135+
136+
$actual = Rules::fromColumn('context', $column);
137+
138+
$this->assertContains('integer', $actual);
139+
$this->assertContains('exists:users,id', $actual);
140+
}
141+
131142
#[Test]
132143
public function forColumn_returns_gt0_rule_for_unsigned_numeric_types(): void
133144
{

0 commit comments

Comments
 (0)