1

Hi guys I'm working on API but I need to validate some data at backend, in this case, we only need a postman to send parameters and headers.

All is working fine now but I need more useful data in each request, Laravel has by default a Validator Form Request Validation, but I don´t know how to use at API side.

I need to send the error message in JSON to Postman.

I found two options, one, make validations into a controller but seems to much code and the other make a php artisan make:request StoreObjectPost and then import the request into the controller and change the request of the store method, which one do you recommend, Ty!

4 Answers 4

4

You could instantiate the validator yourself like this:

$validator = Validator::make($request->all(), [
    'name' => 'min:5'
]);

// then, if it fails, return the error messages in JSON format
if ($validator->fails()) {    
    return response()->json($validator->messages(), 200);
}
Sign up to request clarification or add additional context in comments.

Comments

3
$PostData = Input::all();
$Validator = Validator::make(array(
     'name' => $PostData['name']
      ), array(
      'name' => 'required'
));
if ($Validator->fails()) { //if validator is failed
   return false;
} else {
      // do some thing here
}

Hope this may help you

Comments

1

You should override response(array $errors) method of FormRequest.

public function response(array $errors)
{
    //Format your error message

    if ($this->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}

Comments

0

I prefer the second option. We will be able to keep our controller clean that way, even when we use many validations for the data or using custom error message in the validation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.