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

[5.3] Ability to get message using implicit keys from MessageBag #15063

Merged
merged 2 commits into from
Aug 26, 2016
Merged

[5.3] Ability to get message using implicit keys from MessageBag #15063

merged 2 commits into from
Aug 26, 2016

Conversation

themsaid
Copy link
Member

@themsaid themsaid commented Aug 26, 2016

In Array validation the error messages are keyed by the explicit field name, for example: name.0, name.4, ...

Thus retrieving messages by key requires using the explicit key $errors->get('name.1'), however we won't know which member of the array has an error, so it makes sense to be able to get messages using an implicit address name.*.

In the normal situation the result of get() is an array of messages for that field, eg:

// $errors->get('name.0');
["name.0 is required."]

in case of an array field the result is going to be like this:

// $errors->get('name.*');
[
  "name.0" => [
    "name.0 is required."
  ],
  "name.4" => [
    "name.4 is required."
  ]
]

I'm also thinking of an alternative output that collects messages of all fields in 1 array:

["name.0 is required.", "name.4 is required."]

}

return [];
return $output;
Copy link
Member

Choose a reason for hiding this comment

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

The following refactor might be more suitable:

public function get($key, $format = null)
{
    // If the message exists in the container, we will transform it and return
    // the message. Otherwise, we'll return an empty array since the entire
    // methods is to return back an array of messages in the first place.
    if (array_key_exists($key, $this->messages)) {
        return $this->transform($this->messages[$key], $this->checkFormat($format), $key);
    }

    $output = [];

     if (Str::contains($key, '*')) {
        foreach ($this->messages as $messageKey => $messages) {
            if (Str::is($key, $messageKey)) {
                $output[$messageKey] = $this->transform($messages, $this->checkFormat($format), $messageKey);
            }
        }
    }

    return $output;
}

@themsaid
Copy link
Member Author

@GrahamCampbell thank you, that looks better indeed. Also updated the comment.

@taylorotwell taylorotwell merged commit 3ee569a into laravel:5.3 Aug 26, 2016
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

3 participants