Is it possible to customize the return of the Laravel validation when using Request?

Asked

Viewed 127 times

2

When I use a request post and check the data using Request in Laravel 5.2 via ajax, the data is automatically returned to javascript. I wonder if there is a way for me to capture and customize this data the way I want to return without having to use the validator()?

  • Related: http://answall.com/a/127960/4995

  • Exemplifie what you want to do, maybe with that you’ll be clearer.

  • 1

    You can create the validation manually: https://laravel.com/docs/5.2/validation#other-validation-approaches

  • It is not about creating manual validation, but about dealing with the return of the validation.

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);
}

Thus, when checking whether an exception is actually an instance of ValidationException and the request corresponds to a request XhttpRequest, you can issue a customised response as desired.

I had already explained this in that reply:

Laravel - Test script errors to return certain status to AJAX

Browser other questions tagged

You are not signed in. Login or sign up in order to post.