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

[9.x] Allow invokable rules to push messages to nested (or other) attributes #42801

Merged
merged 1 commit into from
Jun 15, 2022

Conversation

timacdonald
Copy link
Member

This allows invokable validation rule classes to push errors to nested or other attributes. This allows greater integration with the validator and allows userland rules to validate rich object structures, but apply errors to the correct keys.

class UserRule implements InvokableRule
{
    public function __invoke($attribute, $value, $fail)
    {
        if (! is_array($attribute) || array_is_list($attribute)) {
            return $fail('Must be an object.'); // apply to $attribute
        }

        if (! array_key_exists('name', $attribute)) {
            return $fail("{$attribute}.name", 'Is required.'); // apply to nested attribute
        }

        /* ... */
    }
}

Potential error messages...

Validator::make(
    [
        'user_1' => ['xxxx'],
        'user_2' => ['age' => 23],
    ],
    [
        'user_1' => [new UserRule()],
        'user_2' => [new UserRule()],
    ]
);

// errors...

[
    'user_1' => ['Must be an object.'],
    'user_2.name' => ['Is required.'],
]

This feature allows developers to create validation rules that can handle rich objects and validate not only the top level value, but also nested values.

In combination with the DataAware interface, a developer may also push validation errors to other keys. For example a developer could re-create the prohibits validation rule, but put the error message on the attribute that should not exist, rather than the attribute that specified the validation rule.

@timacdonald timacdonald marked this pull request as draft June 14, 2022 03:56
@timacdonald timacdonald marked this pull request as ready for review June 14, 2022 04:00
@timacdonald timacdonald changed the title [9.x] Allow invokable rules to push messages to other attributes [9.x] Allow invokable rules to push messages to nested (or other) attributes Jun 14, 2022
@ankurk91
Copy link
Contributor

Tim, you are on fire 🔥

@taylorotwell taylorotwell merged commit 91877c9 into laravel:9.x Jun 15, 2022
@timacdonald
Copy link
Member Author

❤️

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