Laravel Form Validation redirecting to web routes when it fails

80 views Asked by At

I have a Laravel app (v10.30.1) this api routes block:

<?php

use App\Http\Controllers\EmployeeController;
use Illuminate\Support\Facades\Route;

Route::prefix('v1')->group(function () {
    Route::resource('employees', EmployeeController::class)
        ->only(['store', 'index', 'update']);
});```

This method in EmployeeController:

/**
 * Update an existing employee.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \App\Models\Employee  $employee
 * @return \Illuminate\Http\JsonResponse
 */
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, \Illuminate\Contracts\Validation\ValidationRule|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  \Illuminate\Http\Request  $request
     * @param  \App\Models\Employee  $employee
     * @return \Illuminate\Http\JsonResponse
     */
    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

There are 2 answers

6
shahin On

I think if you set Content-Type:application/json in your header request, the problem will be solved.

1
Adi On

So per our conversation in comments and some context from here Adding failedValidation() function to Request gives error with Illuminate\Contracts\Validation\Validator, but passedValidation() works fine? Maybe you can try overriding the failedVaidation in your form request like this

protected function failedValidation(Validator $validator) {
    $response = new JsonResponse(['errors' => $validator->errors()], 400);
    throw new \Illuminate\Validation\ValidationException($validator, $response);
}

Hope this helps