but I'm getting the error BadMethodCallException: Method Illuminate\Validation\Validator::validateExists:tags,name does not exist. and if I dump the $value it's always null. What am I doing wrong?
The issue you're encountering is due to the incorrect use of the Rule::exists method within the forEach closure. The Rule::exists method is not designed to be used in this way. Instead, you should use the exists validation rule directly in your validation array.
Here's how you can properly validate an array of IDs to ensure each tag exists in the tags table:
use Illuminate\Validation\Rule;
use App\Models\Tag;
// Assuming you're in a controller method or a form request
$request->validate([
'tags' => 'required|array',
'tags.*' => [
'required',
Rule::exists(Tag::class, 'name'),
],
]);
Explanation:
'tags' => 'required|array': This ensures that the tags field is present and is an array.
'tags.*' => [...]: This applies the validation rules to each element within the tags array.
Rule::exists(Tag::class, 'name'): This checks that each tag name exists in the name column of the tags table. The exists rule is used here to ensure that each tag in the array corresponds to an existing record in the database.
By using the exists rule directly in the validation array, you avoid the BadMethodCallException and ensure that each tag is validated correctly.
After writing this response I think I'm doing something wrong anyway, because I want to check the existence using the ilike comparison and I think the Rule::exists(Tag::class, 'name') would check with the = operator