Here we go :-)
First you make a request that validates your input.
It could look something like this
class DummyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'question.options' => [
new OptionsRule(),
]
];
}
}
Then you create a new Rules object (you can do this via php artisan make:rule OptionsRule)
The rule could look something like this
class OptionsRule implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$allValues = collect($value);
foreach ($value as $option) {
$allValues->push($option['label']);
}
return $allValues->count() === $allValues->unique->count();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The validation error message.';
}
}
This is a very shallow implementation that will just loop over $value.
$value is an array of all options for the question that came in via the request.
Here i just push all labels into a new collection and then compare the count of the entire collection (including possible duplicates) to the unique values (more information on the Collection methods in laravel can be found here: https://laravel.com/docs/8.x/collections#available-methods
My implementation is a bit shallow in the sense that i dont keep track of duplicated values.
So rendering a descriptive message to the user might be a bit tricky now.
This could easily be solved by keeping track of the duplicated values separately for example.
the message() method in the OptionsRule is responsible for rendering/returning the validation message to the user.
Hope that this can help getting you started ;-)