Get a JSON response after laravel validation

Donald Kagunila
Feb 3, 2019 · 2 min read
Image for post
Image for post
Photo by Annie Spratt on Unsplash

When creating an API we often have two great worries, one is the connection between the frontend and the backend (eg: Authentication), and the second is error handling, with this short page we are going to look into the latter.

Laravel Validation

Laravel offers out of the box a validation class, you can import it and use it to validate any data using rules already set. To import validation add the following line on top of the class you want to use it,

use Illuminate\Support\Facades\Validator;

Now that you have the validation methods at your disposal, here is how you use it, If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated

public function validateData($data){   $validator = Validator::make($data, [
'field' => ['rule', 'another_rule'],
]);
}

with the given function you will have no response unless you have prepared your template for any error messages, here is how this is typically done in blade templates provided by

@if ($errors->has('field'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('field') }}</strong>
</span>
@endif

Now to get a response when validation fails (when rules fail) we need to add an if statement as follows

if($validator->fails()){
return response()->json($validator->messages(), 200);
}

So the complete function would look like this

public function validateData($data){ $validator = Validator::make($data, [
'field' => ['rule', 'another_rule'],
]);
if($validator->fails()){
return response()->json($validator->messages(), 200);
}
}

With the above function, the response will be converted to json and have the http status code 200,

Mostly you would need this in a form validation code so replace the data with request

public function validateData(Request $request){$validator = Validator::make($request->all(), [
'field' => ['rule', 'another_rule'],
]);
if($validator->fails()){
return response()->json($validator->messages(), 200);
}
}

Thank you for reading, feel free to comment any additional details.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store