Skip to content

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

Merged
taylorotwell merged 2 commits into
laravel:12.xfrom
stevebauman:rule-contains
May 26, 2025
Merged

[12.x] Add Rule::contains#55809
taylorotwell merged 2 commits into
laravel:12.xfrom
stevebauman:rule-contains

Conversation

@stevebauman

Copy link
Copy Markdown
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
Copy Markdown
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
Copy Markdown
Member

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

@stevebauman

Copy link
Copy Markdown
Contributor Author

@taylorotwell For sure!

@stevebauman

Copy link
Copy Markdown
Contributor Author

Done: laravel/docs#10457

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

Copy link
Copy Markdown
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
Copy Markdown
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