How to show validation errors in laravel api while having a form request file separate from controller

Viewed 9119

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

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

You will not be able to fetch the errors in that way since the FormRequest will throw an exception before the request reaches your controller in the event that there is a validation error. However, you can catch the error in the form request it self and modify the response there using the failedValidation method

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class OrderRequest extends FormRequest
{
    public function authorize()
    {
        //
    }

    public function rules()
    {
        //
    }

    public function failedValidation(Validator $validator)
    {
        $errors = $validator->errors(); // Here is your array of errors
        throw new HttpResponseException($errors);
    }
}

I think that's not possible, but you can use the prepareForValidation() method within you FormRequest and manipulate data before validate.

Even when using form request, Laravel handles validation for you automatically without you doing anything. On failed validation, an errors will be returned that you can access in your request response. response.data.errors (depending on the library you use for requests, of course) will contain the errors. For example:

errors: {
    name: ["The name must be at least 2 characters"]
}

This is just a dummy example. Do a quick test by forcing the request to fail and console log the response to see how it will show.

Related