Skip to content
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

[11.x] Provide context for NestedRules #51160

Merged
merged 1 commit into from
Apr 22, 2024

Conversation

imahmood
Copy link
Contributor

@imahmood imahmood commented Apr 22, 2024

In the forEach closure, $data containing all the validation data, while $context provides the specific data associated with the current iteration.
This helps to add validation rules based on the context of each field being validated.

// Sample Code
$formData = [
    'users' => [
        ['id' => 1, 'name' => 'Foo', 'file' => ''],
        ['id' => 2, 'name' => 'Bar', 'file' => ''],
    ],
];

$validator = Validator::make($formData, [
    'users.*.file' => Rule::forEach(function ($value, $attribute, $data, $context) {
        dump($data);
        // Output:
        // [
        //   'users.0.id' => '1',
        //   'users.0.name' => 'Foo',
        //   'users.0.file' => '',
        //   'users.1.id' => '2',
        //   'users.1.name' => 'Bar',
        //   'users.1.file' => '',
        // ]

        dump($context);
        // Output:
        // [
        //   'id' => '1',
        //   'name' => 'Foo',
        //   'file' => '',
        // ]

        return [
            $this->userHasAvatar($context['id']) ? 'nullable' : 'required'
        ];
    }),
]);

@taylorotwell taylorotwell merged commit 1355ba2 into laravel:11.x Apr 22, 2024
30 checks passed
@imahmood imahmood deleted the context-aware-nested-rules branch April 22, 2024 15:29
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.

None yet

2 participants