Skip to content

[12.x] Add Rule::contains #55809

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 26, 2025
Merged

Conversation

stevebauman
Copy link
Contributor

Description

This PR adds a new Contains class and contains method to the Illuminate\Validation\Rule class.

It compiles into the existing contains validation rule string to check if an array contains all of the specified values.

Purpose

Laravel currently includes Rule::in(...) and Rule::array(...) to assist in creating their respective validation rules that contain enums, constants, and arrayables (collections, etc.). Having a method for the contains rule assists in this as well.

Usage

Before:

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

After:

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

@Muffinman
Copy link
Contributor

Rule::enum() does already exist but I can see other cases where this would be useful.

@taylorotwell taylorotwell merged commit 3a9fa02 into laravel:12.x May 26, 2025
61 checks passed
@taylorotwell
Copy link
Member

@stevebauman could you send a docs PR for this one?

@stevebauman
Copy link
Contributor Author

@taylorotwell For sure!

@stevebauman
Copy link
Contributor Author

Done: laravel/docs#10457

public function __toString()
{
$values = array_map(function ($value) {
$value = enum_value($value);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stevebauman doesnt that reference a method registered in orchestra? Not sure if that dependency is wanted.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@patriziotomato

function enum_value($value, $default = null)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants