Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

api

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);
}
like image 206
JoshGray Avatar asked Dec 22 '22 22:12

JoshGray


2 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

like image 184
Adam Avatar answered Dec 28 '22 06:12

Adam


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
like image 35
Erkan Özkök Avatar answered Dec 28 '22 05:12

Erkan Özkök