10000 [11.x] Fluent Array validation by Ahmad-Mohammad-Kouja · Pull Request #54517 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content

[11.x] Fluent Array validation #54517

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

Conversation

Ahmad-Mohammad-Kouja
Copy link
@Ahmad-Mohammad-Kouja Ahmad-Mohammad-Kouja commented Feb 8, 2025

This pull request introduces a new fluent array validation class, offering a more elegant and expressive way to define array validation rules.

Before this PR, arrray validation required string-based rules:

$rules = [
    'array' => ['required', 'array', 'min:3', 'max:5', 'list'],
    'array_with_specific_elements' => ['required', 'array:a,b,c']
];

To use the fluent array validation:

use Illuminate\Validation\Rule;

$rules = [
    'array' => [
       'required',
        Rule::array()
            ->min(3)
            ->max(5)
            ->list();
    ],
    'array_with_specific_elements' => ['required', Rule::array(['a', 'b', 'c'])],
];

Available methods

  • distinct(bool $strict = false)
  • max(int $max)
  • min(int $min)
  • between(int $min, int $max)
  • size(int $size)
  • contains($keys)
  • inArray(string $anotherField)
  • list()

$this->keys = is_array($keys) ? $keys : func_get_args();
$keys = is_array($keys) ? $keys : func_get_args();

if (empty($keys)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

You could do this without a function call:

Suggested change
if (empty($keys)) {
if ($keys === []) {

Choose a reason for hidi 8000 ng this comment

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

yes you are right i update it

Comment on lines +39 to +42
$keys = array_map(
static fn ($key) => enum_value($key),
$keys,
);
Copy link
Contributor

Choose a reason for hiding this comment

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

You can simplify this to a first-class callable:

Suggested change
$keys = array_map(
static fn ($key) => enum_value($key),
$keys,
);
$keys = array_map(enum_value(..), $keys);

@taylorotwell
Copy link
Member

I don't think this is adding much benefit. It feels like we're just adding more fluent rules for fun now.

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.

3 participants
0