Is it possible to customize the return of laravel validation when I use the Request?

2

When I use a post request and validate the data using the Request in Laravel 5.2 via ajax, the data is automatically returned to javascript. I would like to know if there is a way I can capture and customize this data the way I want it to return without having to use validator() ?

    
asked by anonymous 17.05.2016 / 22:45

1 answer

2

Change the file app/Exceptions/Handler.php and add the following lines:

public function render($request, Exception $e)
{

    if ($e instanceof \Illuminate\Validation\ValidationException && $request->ajax())
    {
        return response()->json(['success' => false, 'detail' => (string) $e], 422);
    }

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

So by checking if an exception is actually an instance of ValidationException and the request matches a XhttpRequest request, you can issue a custom response as desired.

I had already explained this in this answer:

Laravel - Test script errors to return certain status for AJAX

    
14.12.2016 / 16:43