Skip to content

Commit

Permalink
Throw exception if column is not exists in unique rule
Browse files Browse the repository at this point in the history
  • Loading branch information
Lakshan-Madushanka committed Aug 15, 2024
1 parent 0b85e15 commit b4360c1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Illuminate/Validation/Concerns/ValidatesAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Exceptions\MathException;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Exists;
use Illuminate\Validation\Rules\Unique;
Expand Down Expand Up @@ -959,6 +960,21 @@ public function validateUnique($attribute, $value, $parameters)
// assume that this column to be verified shares the attribute's name.
$column = $this->getQueryColumn($parameters, $attribute);

$model = new class extends Model {};
$model->setTable($table);

// Get columns of $table
$availableColumns = Schema::getColumnListing($table);
$availableQualifyColumns = $model->qualifyColumns($availableColumns);

$columns = array_merge($availableColumns, $availableQualifyColumns);

if (!in_array($column, $columns)) {
$columnsList = implode(',', $columns);
$errorMsg = sprintf("The [%s] column doesnt exists in [%s] the table. Available columns: {$columnsList}", $column, $table);
throw new InvalidArgumentException($errorMsg);
}

$id = null;

if (isset($parameters[2])) {
Expand Down
3 changes: 3 additions & 0 deletions tests/Integration/Validation/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ public function testUnique()

$validator = $this->getValidator(['first_name' => 'Taylor'], ['first_name' => 'unique:'.User::class]);
$this->assertTrue($validator->passes());

$validator = $this->getValidator(['first_name' => 'Taylor'], ['first_name' => 'unique:'.User::class.',no_column']);
$this->assertThrows(fn() => $validator->passes(), \InvalidArgumentException::class);
}

public function testUniqueWithCustomModelKey()
Expand Down

0 comments on commit b4360c1

Please sign in to comment.