I have a Laravel app (v10.30.1) this api routes block:
<?php
use AppHttpControllersEmployeeController;
use IlluminateSupportFacadesRoute;
Route::prefix('v1')->group(function () {
Route::resource('employees', EmployeeController::class)
->only(['store', 'index', 'update']);
});```
This method in EmployeeController:
/**
* Update an existing employee.
*
* @param IlluminateHttpRequest $request
* @param AppModelsEmployee $employee
* @return IlluminateHttpJsonResponse
*/
public function update(EmployeeUpdateRequest $request, Employee $employee): JsonResponse
{
$employee->update($request->validated());
return response()->json($employee, 200);
}
This is the EmployeeUpdateRequest:
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, IlluminateContractsValidationValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'cpf' => 'required|size:11|unique:employees',
];
}```
When the validation pass, it works fine, but when it fails, instead of return the error message in a json format, it is redirecting to home web route.
If i create the Validator mannually like this, it works fine, but for now i’d need to use a form request:
/**
* Update an existing employee.
*
* @param IlluminateHttpRequest $request
* @param AppModelsEmployee $employee
* @return IlluminateHttpJsonResponse
*/
public function update(Request $request, Employee $employee): JsonResponse
{
$validator = Validator::make($request->all(), [
'cpf' => 'size:11|unique:employees',
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 400);
}
$employee->update($request->all());
return response()->json($employee, 200);
}```
I'm expecting to use a form request and just receive the error messages when it happens instead of be redirected to web home route
2
Answers
I think if you set
Content-Type:application/json
in your header request, the problem will be solved.So per our conversation in comments and some context from here Adding failedValidation() function to Request gives error with IlluminateContractsValidationValidator, but passedValidation() works fine?
Maybe you can try overriding the
failedVaidation
in your form request like thisHope this helps