Get a JSON response after laravel validation

Donald Kagunila
Feb 3 · 2 min read
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.