Laravel validation always returns 200 OK from API
If you are requesting from postman then always check header and set
Accept = 'application/json'
You should make sure you're sending the request with the Accept: application/json
header.
Without that - Laravel won't detect that it's an API request, and won't generate the 422 response with errors.
The proper way to display validation errors using injected FormRequest
object is to override failedValidation
.
As stated previously in comment section, injected FormRequest
object validates the request by itself, no need to validate it a second time in the controller body (that's one of the main benefit of it). If the validation fails, you won't hit the controller body anyway.
Create an abstract class that extends FormRequest
and override failedValidation
.
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Response;
abstract class BaseFormRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
abstract public function rules(): array;
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
abstract public function authorize(): bool;
/**
* Handle a failed validation attempt.
*
* @param Validator $validator
*
* @return void
*/
protected function failedValidation(Validator $validator): void
{
$errors = $validator->errors();
throw new HttpResponseException(response()->json([
'errors' => $errors
], Response::HTTP_UNPROCESSABLE_ENTITY));
}
}
You can now extends BaseFormRequest
on all your APIs request validation classes. Validation errors will now be displayed as a JSON encoded message with a Unprocessable Entity (422) HTTP code.
Source : https://medium.com/@Sirolad/laravel-5-5-api-form-request-validation-errors-d49a85cd29f2
I solved the problem with adding more code in my PostRequest.php
public $validator = null;
protected function failedValidation($validator)
{
$this->validator = $validator;
}
and I show the error message by using controller
if (isset($request->validator) && $request->validator->fails()) {
return response()->json([
'error_code'=> 'VALIDATION_ERROR',
'message' => 'The given data was invalid.',
'errors' => $request->validator->errors()
]);
}