Skip to content

[5.5] Change message to array_first($this->errors(), 'The given data was invalid.') ? #21059

Closed
@medz

Description

@medz

parent::__construct('The given data was invalid.');

change message to array_first($this->errors(), 'The given data was invalid.')

Will this change be better?

parent::__construct('The given data was invalid.');

To

parent::__construct(array_first(
    $this->errors(),
    'The given data was invalid.'
));

Activity

changed the title [-]change `message` to `array_first($this->errors(), 'The given data was invalid.')` ?[/-] [+][5.5] Change `message` to `array_first($this->errors(), 'The given data was invalid.')` ?[/+] on Sep 7, 2017
themsaid

themsaid commented on Sep 7, 2017

@themsaid
Member

The current code is fine, you can construct the output message to your users as you wish in the Exception Handler.

setefocos

setefocos commented on Sep 19, 2017

@setefocos

It is actually a bit strange because it is fixed in english. My systems aren't. I can't realyze why it was changed this way. I'm not complaining but I'm having trouble to understand it. I'm trying to figure out the best way to deal with this fixed english message in every single validation not passing. I'm using
Form Requests. Any help will be wellcome.

nonDeath

nonDeath commented on Sep 19, 2017

@nonDeath

Best to add that message in resources/lang/{lang_code}/validation, as a new entry:

message => 'The given data was invalid'

And pass it to the contructor of the exception. Because maybe we are not English speakers.

Regards!!!

jansenfelipe

jansenfelipe commented on Dec 11, 2017

@jansenfelipe

Work around this problem, I added in the render() method of the file app\Exceptions\Handler.php

if ($exception instanceof ValidationException)
  return response()->json(['message' => 'Os dados fornecidos não são válidos.', 'errors' => $exception->validator->getMessageBag()], 422);
medz

medz commented on Dec 12, 2017

@medz
Author

@janhartigan I also think it's best to add as a message to a language pack because not everyone is in English.

mgambati

mgambati commented on Jan 26, 2018

@mgambati

Why is this closed? I really need to translate this string.

peterviergutz

peterviergutz commented on Feb 1, 2018

@peterviergutz

@themsaid how about Commands and Jobs? The fact that a ValidationException is being thrown already tells me that "the given data was invalid", but having the real error message in e.g. horizon trace of the failed job and in the apps language by default would absolutely make sense, no?

I'd suggest:

parent::__construct(array_first(
    $this->errors(),
    trans('validation.default')
));
TimOgilvy

TimOgilvy commented on Sep 1, 2018

@TimOgilvy

Not only is this a case of "not everyone speaks English"... not everyone even speaks the same dialect of English. I thought one of my dev team members was being super stuffy and vague, until I realised it wasn't lang-pack at all. Maybe it's just coz I am from 'Straya mate, ukno the big place downunda?

"the given data is invalid" sounds like something a robotic maths professor would say in a red-pen note on a third year mathematics dissertation, not something a user interface should provide as feedback.

All I want is to change mine to say "There was an error with the data you provided". Like a person might say... rather than "Does ... not.. compute...".

"The given data was invalid"... is some weird 18th century phrasing.

Lang pack for everyone!!! 😁

vladan-me

vladan-me commented on Dec 7, 2018

@vladan-me

Work around this problem, I added in the render() method of the file app\Exceptions\Handler.php

if ($exception instanceof ValidationException)
  return response()->json(['message' => 'Os dados fornecidos não são válidos.', 'errors' => $exception->validator->getMessageBag()], 422);

Have to be careful with ValidationException since it throws it both for web and api routes. Therefore, since this one is strictly for api it should likely look like:

if ($exception instanceof ValidationException && $request->expectsJson())

supersede

supersede commented on Feb 7, 2019

@supersede

Sorry for necro, just wanted to confirm that whenever validation fails we always get the "message" key in the response ? (no matter what language)

jamesfairhurst

jamesfairhurst commented on Mar 13, 2020

@jamesfairhurst
Contributor

An old issue but I encountered a similar need to change the message, looks like you can pass in a response as the 2nd argument to ValidationException which will be returned in the handler. I wanted to do this inside a FormRequest so I overrode the failedValidation method:

protected function failedValidation(Validator $validator)
{
    $response = response()->json([
        'message' => 'Custom message here',
        'errors' => $validator->errors()->messages(),
    ], 422);

    throw new ValidationException($validator, $response);
}
fjmoralesp

fjmoralesp commented on Apr 11, 2020

@fjmoralesp

Work around this problem, I added in the render() method of the file app\Exceptions\Handler.php

if ($exception instanceof ValidationException)
  return response()->json(['message' => 'Os dados fornecidos não são válidos.', 'errors' => $exception->validator->getMessageBag()], 422);

By doing that you are affecting this logic:

    /**
     * Create a response object from the given validation exception.
     *
     * @param  \Illuminate\Validation\ValidationException  $e
     * @param  \Illuminate\Http\Request  $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function convertValidationExceptionToResponse(ValidationException $e, $request)
    {
        if ($e->response) {
            return $e->response;
        }

        return $request->expectsJson()
            ? $this->invalidJson($request, $e)
            : $this->invalid($request, $e);
    }

In my case to overwrite the invalidJson method was a little bit more consistent:

    /**
     * Convert a validation exception into a JSON response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Validation\ValidationException $exception
     * @return \Illuminate\Http\JsonResponse
     */
    protected function invalidJson($request, ValidationException $exception): JsonResponse
    {
        return response()->json([
            'message' => trans('validation.invalid'), // custom validation.php lang key
            'errors' => $exception->errors(),
        ], $exception->status);
    }
cautionbug

cautionbug commented on Apr 20, 2020

@cautionbug

@jamesfairhurst i landed here looking for a way to override the Exception not to deal with translation but to implement a specific set of Exception subclasses. Your suggestion is exactly what i needed: succinct, easy to implement, and i can isolate it only to places where i'm using my particular FormRequest subclasses. Thank you!

As for this two year old issue - not surprised that the least liked response is also the one that closed the issue without discussion. i hope when i move forward from 5.3 that things like this are addressed for broader linguistic and architectural needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @jamesfairhurst@peterviergutz@nonDeath@mgambati@cautionbug

        Issue actions

          [5.5] Change `message` to `array_first($this->errors(), 'The given data was invalid.')` ? · Issue #21059 · laravel/framework