Skip to content

Commit

Permalink
Fix exists rule when using foreign reference (#722)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicodevs authored Dec 27, 2024
1 parent 2a743d5 commit e4a7397
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Translators/Rules.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
11 changes: 11 additions & 0 deletions tests/Feature/Translators/RulesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down

0 comments on commit e4a7397

Please sign in to comment.