Laravel's Rule::contains() Method: Consistent Fluent Validation for Arrays

Laravel's Rule::contains() Method: Consistent Fluent Validation for Arrays

Laravel's validation system just got more consistent with the addition of Rule::contains() for arrays, matching the fluent interface pattern you're already familiar with from other validation rules.

The Laravel ecosystem has always prioritized consistency and developer experience, and the new Rule::contains() method exemplifies this philosophy perfectly. While Laravel has long supported fluent validation rules through the Rule class for scenarios like Rule::in(), Rule::exists(), and Rule::unique(), array validation with the contains rule required falling back to string-based syntax with manual concatenation.

The Rule::contains() method brings array validation into the same fluent interface ecosystem, eliminating the need for cumbersome string building and making your validation rules more readable and maintainable.

Real-World Example

Consider a user management system where you need to validate that submitted roles contain at least one administrative role. Previously, this required manual string construction:

use Illuminate\Validation\Rule;

enum Role: string
{
    case Admin = 'admin';
    case Editor = 'editor';
    case Viewer = 'viewer';
    case Moderator = 'moderator';
}

// Before: Manual string concatenation
Validator::make($request->all(), [
    'roles' => [
        'required',
        'array',
        'contains:'.implode(',', array_column([Role::Admin, Role::Editor], 'value')),
    ],
]);

// After: Clean fluent interface
Validator::make($request->all(), [
    'roles' => [
        'required',
        'array',
        Rule::contains([Role::Admin, Role::Editor]),
    ],
]);

$validRequest = [
    'roles' => [
        Role::Admin->value,
        Role::Viewer->value
    ]
];

This approach is particularly valuable when working with enums, dynamic role systems, or any scenario where you need to validate that an array contains specific values from a predefined set. The fluent interface makes the validation intent immediately clear and reduces the cognitive load of parsing concatenated strings.

The Rule::contains() method also integrates seamlessly with other array validation rules and maintains consistency with Laravel's broader validation API. This consistency reduces context switching and makes validation rules more predictable for developers already familiar with Laravel's patterns.

Stay Updated with More Laravel Tips

Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe