2

I need to validate a request with image and tags. How to return a common validation error message for tags.

$this->validate($request, [
    'image' => 'required|image,
    'tags.*' => 'string'
]);

Currecnt message is.

{
    "image": [
        "The image field is required."
    ],
    "tags.0": [
        "The tags.0 must be a string."
    ],
    "tags.1": [
        "The tags.1 must be a string."
    ]
}

Expected message is.

{
    "image": [
        "The image field is required."
    ],
    "tags": [
        "The tags must be a string."
    ]
}

3 Answers 3

1

Have you tried this,

$this->validate($request, [
    'image' => 'required|image,
    'tags.*' => 'string'
],$messages = [
    'tags.*' => 'The tags must be a string.'
]);

I'm not quit sure but this might work for you.

Sign up to request clarification or add additional context in comments.

6 Comments

The message changed. but it comes on multiple array index. "tags.0": [ "The tags must be a string." ], "tags.1": [ "The tags must be a string." ]
@noufalcep This is because you have multiple incorrect fields of array input field
Yes. I need a single error message for the multiple inputs.
@noufalcep you can do it in in view. just take single message from array of message but it's not a good way
I can't do it in view. I will find another solution.
|
0

I think you should try with similar below example:

public function messages()
        {
            $messages = [];
            foreach ($this->request->get('tags') as $key => $val) {
                $messages['tags.' . $key . '.string'] = 'The tags must be a string.'
            }
            return $messages;
        } 

Hope this work for you !!!

Comments

0

You can add messages with a * to your translation file, as documented.

'custom' => [
    'tags.*' => [
        'string' => 'The tags must be a string.',
    ]
],

1 Comment

The message changed. but it comes on multiple array index. "tags.0": [ "The tags must be a string." ], "tags.1": [ "The tags must be a string." ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.