oldgit liked a comment+100 XP
5mos ago
You can also enhance this by adding a unique constraint in the database.
$table->unique(['number', 'competition_id']);
oldgit wrote a reply+100 XP
5mos ago
Thanks, I'll have a look at that.
oldgit liked a comment+100 XP
5mos ago
You have to create a custom Rule.
public function rules(): array
{
return [
'competition_id' => ['required', 'exists:competitions,id'],
'number' => [
'required',
Rule::unique('entries', 'number')
->where(function ($query) {
$query->where('competition_id', $this->competition_id);
}),
],
];
}
oldgit started a new conversation+100 XP
5mos ago
I'm trying to validate a piece of data against a subset of records in a table. The big picture is that I have a table of competiton entries for multiple competitions. Each entry must have a unique number (to be displayed by the entrant) for obvious reasons. The Entry table includes a field - competitionID - which links the Entry to the Competition. I can easily use the 'unique' validator to validate against the whole entries table. Any suggestions for how I can validate it, in simple terms, 'unique where competitionID = $x'
TIA, Alex