I have a form request file handling my validations separate from my controller. How do i return validation errors after an api call within the controller?
//my controller
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function orders(GetOrdersRequest $request, OrderRepository $orderRepository)
{
$order = $orderRepository->allOrders($request->paginate);
return $this->sendSuccess('Orders retrieved successfully', $order);
}
In the FormRequest class there is a function called failedValidation
:
protected function failedValidation(Validator $validator)
{
throw (new ValidationException($validator))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl());
}
It triggers when your validation fails. For API endpoints, this request is a bad response because it is a redirect and contains way too much information. To return a clean and
lightweight json respond, simply oerwrite the function failedValidation
in your FormRequest for a matching response for your API. For example like this:
protected function failedValidation(Validator $validator)
{
$errors = $validator->errors();
$response = response()->json([
'message' => 'Invalid data send',
'details' => $errors->messages(),
], 422);
throw new HttpResponseException($response);
}
Credit to https://stackoverflow.com/a/56726819/2311074
Laravel request class returns back automatically when validation fails. You should show your error messages in view(blade) file. You can follow official documentation.
For API's it returns automatically a JSON response including error messages.
Basically you can do it in blade file:
@if($errors->has('email'))
<span class="error">{{ $errors->get('email') }}</span>
@endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With