Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

willsthebills's avatar

Custom FormRequest redirects to web route in Laravel 11

I have an application in Laravel 11 that is configured as follows in the app.php file:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        apiPrefix: 'api/v0',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

In api.php file, I have the following route:

Route::get('/updateAllMovies', [\App\Http\Controllers\APIController::class, 'updateAllMovies']);

Inside my APIController, I have this code:

public function updateAllMovies(APIRequest $request){
        $validated = $request->validated();

        if ($request->fails()) {
            return response()->json(['errors' => $request->errors()], 422);
        }

        return response()->json(['success' => true], 200);
    }

And finally inside my APIRequest I have:

class APIRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'access_token' => 'required|exists:tokens_access,token'
        ];
    }

    public function messages(){
        return [
            'access_token.required' => 'O token de acesso é obrigatório na requisição.',
            'access_token.exists' => 'O token de acesso informado é inválido.'
        ];
    }
}

When I try to make a request to the /updateAllMovies route via postman (Sending the access_token or not.), I am redirected to the main route that exists in the web.php file.

Route::get('/', function () {
    return 'Welcome to my Cinema API 🎥🍿';
});

I would like to understand why this is happening, why don't I continue on the api.php route and don't receive any error messages?

0 likes
1 reply
Snapey's avatar

because validation happens in the request class and your controller will never be reached if there is a validation error.

In postman make sure you send the header Accept: Application/json so that Laravel knows that a json response is required and not a redirection.

1 like

Please or to participate in this conversation.