Validate Symfony Integer and Boolean Query Parameters

Symfony convenience getters convert query parameters, but malformed values should not silently become a useful default. When missing, empty, invalid, and out-of-range values have different meanings, validate explicitly and return a client error for input the endpoint cannot accept.

Last updated: November 13, 2026.

<?php

use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpKernelExceptionBadRequestHttpException;

function readListOptions(Request $request): array
{
    $page = $request->query->filter('page', null, FILTER_VALIDATE_INT, [
        'flags' => FILTER_NULL_ON_FAILURE,
        'options' => ['min_range' => 1, 'max_range' => 10_000],
    ]);

    $drafts = $request->query->filter('drafts', null, FILTER_VALIDATE_BOOL, [
        'flags' => FILTER_NULL_ON_FAILURE,
    ]);

    if ($request->query->has('page') && $page === null) {
        throw new BadRequestHttpException('page must be an integer from 1 to 10000');
    }
    if ($request->query->has('drafts') && $drafts === null) {
        throw new BadRequestHttpException('drafts must be a valid boolean');
    }

    return ['page' => $page ?? 1, 'drafts' => $drafts ?? false];
}

The presence check separates a missing parameter from one that was supplied but failed validation. Defaults apply only when the client omitted the value.

Choose a clear input contract

The Symfony HttpFoundation documentation lists getInt(), getBoolean(), and filter(). The convenience getters are suitable when their conversion behavior matches the endpoint contract. Use filter() when you need to detect invalid values, enforce a numeric range, or distinguish invalid input from an absent value.

An empty query value such as ?page= is present, not missing. Decide whether it is invalid or deliberately equivalent to the default, document that choice, and test it. Do the same for arrays such as ?page[]=2, repeated keys, whitespace, negative numbers, and values beyond the accepted range.

Return useful client errors

The PHP filter_var documentation defines the validation filters and FILTER_NULL_ON_FAILURE. Returning null lets the controller make the policy decision instead of depending on a generic conversion exception.

For an API, translate invalid query input into a stable HTTP 400 response with a short field-specific message. Do not include stack traces or internal class names. Keep authorization separate from validation: a valid drafts=true value does not authorize the caller to view drafts. Add functional tests for every accepted spelling and rejected edge case so framework upgrades cannot silently change the endpoint contract.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov