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