Laravel Validation - How to check if a value exists in a given array?

Laravel Validation - How to check if a value exists in a given array?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Laravel Validation - How to check if a value exists in a given array?

You are encountering an Array to string conversion error because of how the in validation rule processes its second argument. In standard Laravel validation, the in rule expects a single string or a list of strings separated by pipes (e.g., '1|2|3'). When you pass a raw PHP array—specifically via $employee->pluck('id')->toArray()—to the in rule within the rules definition array, Laravel's internal validation engine attempts to convert that entire collection object into a string. Since collections do not have a default string representation, this triggers the exception you are seeing.

The core issue lies in the mismatch between the data structure provided and the expected input format of the validation rule. You cannot simply dump an array directly into the in syntax unless it is formatted as a specific string pattern. To resolve this, you must ensure the validator receives the values in a format it can parse: either a space-pipe-delimited string or a custom rule that explicitly handles an array.

Converting the Collection to a Delimited String

The most straightforward fix involves transforming your collection into a string that Laravel understands as a list of valid options. You can achieve this by joining the array elements with a pipe character (|), which is the standard delimiter for the in rule.

Instead of passing the result of toArray(), you should use implode to create the required string format:

$validIds = $employee->pluck('id')->implode('|');

$this->validate($request, [
    'employee' => 'required|in:' . $validIds,
], [
    'employee.in' => 'employee does not exists',
]);

By converting the collection to a string like "1|2|3", you adhere to the expected input signature of the in rule. This approach requires no custom logic and works seamlessly with Laravel's built-in validation engine. It is important to note that if your IDs contain characters that might be interpreted as delimiters or special regex characters, you should ensure they are sanitized before joining them, though numeric IDs typically do not require this extra step.

Using a Custom Validation Rule

If you prefer to pass an array directly to the validator without stringifying it, you must define a custom validation rule. This is useful when you want to keep your codebase clean or if the list of valid IDs is dynamic and complex.

You can register a custom rule in your AppServiceProvider or create a dedicated class:

use Illuminate\Support\Facades\Validator;

Validator::extend('in_array', function ($attribute, $value, $parameters, $validator) {
    $allowedValues = $parameters[0];
    
    if (!is_array($allowedValues)) {
        return true; // Or throw an error if parameters are malformed
    }

    return in_array($value, $allowedValues, true);
}, 'The :attribute must exist in the provided list.');

Once registered, you can invoke it like this:

$this->validate($request, [
    'employee' => 'required|in_array:' . collect($employee->pluck('id'))->toArray(),
]);

However, note that passing an array directly into the in rule string syntax (even with a custom rule name) often still requires the validator to handle the parsing of the parameter correctly. If your goal is strictly to pass an array without string manipulation, the cleanest approach is often to move the validation logic outside the standard validate helper or use a closure-based rule:

$employeeIds = $employee->pluck('id')->toArray();

$this->validate($request, [
    'employee' => ['required', function ($input) use ($employeeIds) {
        return in_array($input['employee'], $employeeIds, true);
    }],
]);

This closure approach is robust because it bypasses the string-parsing limitations of the in rule entirely. It gives you full control over the comparison logic and error messages, allowing you to provide specific feedback like "employee does not exists" directly in the error response.

Handling Trade-offs and Limitations

When deciding between converting to a pipe-delimited string or using a closure, consider the performance implications. For small lists of IDs (e.g., fewer than 50 items), both methods are negligible. However, if you are validating against a very large list of values passed from an API, the in rule with a long string might be slightly less efficient than checking against an array directly in a closure, as string matching can become costly at scale.

Additionally, always remember to use the third parameter of in_array (set to true) when strict type checking is required. If your backend sends IDs as strings but your database stores them as integers, a loose comparison might cause false negatives. Explicitly defining the array and using strict equality ensures data integrity across different input types.

For more complex validation scenarios involving dynamic arrays or collections from external services, refer to LaravelCompany for advanced patterns on handling collection-based validation in modern Laravel applications.

Our network