Skip to content

Commit 97d70e3

Browse files
Mark Salmonjasonmccreary
authored andcommitted
Adds exists rule for relation key validation
1 parent 69b1ad1 commit 97d70e3

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Translators/Rules.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,11 @@ public static function fromColumn(Column $column, string $context = null)
4646
if (Str::startsWith($column->dataType(), 'unsigned')) {
4747
$rules = array_merge($rules, ['gt:0']);
4848
}
49+
50+
if (Str::endsWith($column->name(), '_id')) {
51+
[$table, $field] = explode('_', $column->name());
52+
$rules = array_merge($rules, ['exists:' . Str::plural($table) . ',' . $field]);
53+
}
4954
}
5055

5156
if (in_array($column->dataType(), [

tests/Feature/Translators/RulesTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,19 @@ public function forColumn_returns_numeric_rule_for_numeric_types($data_type)
9090
public function forColumn_returns_integer_rule_for_integer_types($data_type)
9191
{
9292
$column = new Column('test', $data_type);
93+
$this->assertContains('integer', Rules::fromColumn($column));
94+
}
95+
96+
/**
97+
* @test
98+
* @dataProvider integerDataTypesProvider
99+
*/
100+
public function forColumn_returns_exists_rule_for_foreign_keys($data_type)
101+
{
102+
$column = new Column('test_id', $data_type);
93103

94104
$this->assertContains('integer', Rules::fromColumn($column));
105+
$this->assertContains('exists:tests,id', Rules::fromColumn($column));
95106
}
96107

97108
/**

0 commit comments

Comments
 (0)