Skip to content

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
@imahmood imahmood deleted the context-aware-nested-rules branch April 22, 2024 15:29
@siarheipashkevich
Copy link
Contributor

@imahmood @taylorotwell what about the documentation for this wonderful feature?

@imahmood
Copy link
Contributor Author

@siarheipashkevich Sorry, my English is not good enough to write the documentation.

@siarheipashkevich
Copy link
Contributor

@imahmood got it, anyway, thanks for this feature 👍

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