netdjw
netdjw

Reputation: 6007

How to catch and return errors in Laravel controller after validation?

I'm using this code to validate my $request variable:

$validatedData = $request->validate([
    'name' => 'string|required|max:255',
    'lead' => 'nullable|string',
    ...
]);

After this I want to return error messages as a JSON object, use this code:

return response()->json([
    'errors' => $validatedData->errors()
]);

And here it says $ValidateData is an array. That's true, but where can I find the validation error messages? I checked the official Laravel 5.7 documentation, but it's not clear.

Any idea?

Upvotes: 1

Views: 1323

Answers (1)

Szabó Kevin
Szabó Kevin

Reputation: 56

If you need customoize the error messages, just need to read this in laravel documentation.

https://laravel.com/docs/5.7/validation#customizing-the-error-messages https://laravel.com/docs/5.7/validation#working-with-error-messages

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute value :input is not between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

$validator = Validator::make($input, $rules, $messages);

I hope, i could help for you.

Upvotes: 2

Related Questions