Laravel: How to log errors in form request input

Viewed 2860

I am using Laravel's form request to validate some complex input. If there is an error, Laravel returns the user to the previous page (which is fine), but I also want it to log the errors for me. How do I do that?

I attempted to use the form's withValidator method as follows, but got an error re 'maximum nesting level reached'.

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($validator->fails()) {
            foreach($validator->errors()->all() as $error) {
                logger($error);
            }
        }
    });
}
3 Answers

Calling $validator->fails() in the after callback will end in an endless loop as it calls $validator->after() in the process. It re-evaluates and does not use a previous result.

Use $validator->errors() instead and check if it is empty.

Best way to validate on laravel is to use Laravel Request

As mentioned in the Laravel Documentation,

If the incoming request parameters do not pass the given validation rules, Laravel will automatically redirect the user back to their previous location.

In addition, all of the validation errors will be present in the $error variable.

The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

To view the errors, you can add the following snippet inside your view which is returned when the validation is failed:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
Related