Laravel Easiest way to log the Form Request Validation actual error messages

2.2k views Asked by At

I am working in Laravel v6.18 project for client.

Now randomly when I try to submit form with quite an amount of data, I am getting the error as below:

[2020-09-17 10:05:23] local.ERROR: Illuminate\Validation\ValidationException: The given data was invalid. in [LaravelDir]\vendor\laravel\framework\src\Illuminate\Foundation\Http\FormRequest.php:130
Stack trace:
....

I know this is a generic error message created to hide the actual error from the end user, but I want the actual error to be logged.

If I want to log this actual error without directly editing the Vendor package, I have to override, but I have no clue which method of which class to override for logging actual Form Request validation error(which Form field validation failed).

Can anyone assist in this ?

2

There are 2 answers

0
mmabdelgawad On BEST ANSWER

I would suggest doing it in Handler file in report method you will check for ValidationException then log the validation errors like so

if ($exception instanceof ValidationException) {
    Log::error("errors", $exception->errors());
}
1
Md. A. Apu On

In newer laravel versions validation exception can't be caught in exception handlers register method.

In laravel 8.x you simply override convertValidationExceptionToResponse method in app/Exceptions/Handler.php file, there you can log validation errors.

like following

public function convertValidationExceptionToResponse(ValidationException $e, $request)
{
    // logging here (i'm using a trait to have custom logger but you can use default logger too)
    $this->logValidationError($request, $e->errors());

    return parent::convertValidationExceptionToResponse($e, $request);
}