Now that i'm reading again your suggestion.
- I can't validate that the input must be a string and contain a comma symbol
The reason is that the input consists of usernames which must exist in the database. Therefore, i can't validate a string with multiple usernames.
Another reason is that a comma is included only when multiple usernames are passed.
What i did in the prepareForValidation method is
public function prepareForValidation()
{
if (!is_string($this->names)) {
return;
}
if (str_contains($this->names, ',')) {
$this->request->merge(
[$this->attribute => $this->splitNames($this->names)]
);
} else {
$this->request->merge(
[$this->attribute => [$this->clean($this->names)]]
);
}
}
And the validation rules are
public function rules()
{
return [
'title' => ['required', 'string', 'min:3'],
'message' => ['required', 'string'],
'participants' => ['required', "array", 'min:1'],
'participants.*' => ['required', 'string', 'exists:users,name'],
];
}
So i expect the input to be string.
If the input is string then check if comma symbol is included and if yes then explode.
Otherwise only one username is in the string and therefore create an array with a single username.
The validation rules expect an array.
If the input is not a string then prepareForValidation will not create an array and the validation will fail.
If the input is a string, then an array will be created as expected and then the validation rules will check if the content of the array are string and if each element ( username ) exists in the database.