Fix database rule failure parameters, validator-scoped conditions and ini-dependent float formatting
Summary
This PR fixes three regressions in the native validation rules work:
failed()and message replacers report the complete parameter list foruniqueandexistsrules again.- Conditions that a
Validatorsubclass adds through parameters or thegetExtraConditions()/getUniqueExtra()hooks combine with a fluent rule's own conditions again, and a manualvalidate*()call no longer inherits the previous rule's conditions. Number::toString()no longer depends on theserialize_precisionini setting.
Purpose
Applications and packages ported from Laravel rely on the first two behaviors: custom replacers and failed() assertions read the extra parameters, and multi-tenant validators scope every database rule from a subclass. Both must keep working when a rule is written with the fluent builders. The third change protects PDO bindings, SQL escaping, decimal casts and validation comparisons from a PHP setting that is outside the framework's control.
Problem
Failure parameters were truncated. Database rules validate from a header (table, column, ignored ID, ID column) plus typed conditions, and only the header reached addFailure().
unique:users,email,9,id,tenant_id,42reported['users', 'email', '9', 'id']instead of all six parameters.- A fluent
Rule::unique()without an ignored ID reported''instead of'NULL'. - The same string rule reported the full list in a
Validatorsubclass and the header only in the baseValidator.
Validator-level scoping was dropped for fluent rules. validateExists() and validateUnique() took their conditions only from the current rule when it was a fluent rule or a captured plan.
- A subclass that appended
tenant_id, 42to$parametersproduced a query withouttenant_id, soexistspassed for another tenant's row. - Conditions added by overriding
getExtraConditions()orgetUniqueExtra()were skipped the same way. - A fluent
uniquerule that declares conditions never reachedgetExtraConditions(), while the equivalent string ruleunique:users,email,NULL,id,active,1did. $validator->validateExists('team', 5, ['teams', 'id', 'tenant_id', '8'])called from anafter()hook ran with the conditions of the last validated rule instead of its own parameters.
Float formatting followed serialize_precision. Number::toString() used json_encode().
- With
serialize_precision=17,19.99was bound as19.989999999999998, sowhere('price', 19.99)on aDECIMALcolumn found no row, andRule::numeric()->max(19.99)rejected the string input'19.99'. - With
serialize_precision=6,1234567.89was bound as1.23457e+6and stored as1234570.00without a warning.
Architecture and Implementation
Failure reporting
DatabaseRulePlankeeps the extra parameters of a string or array rule exactly as written, and gainsfailureParameters(array $header). It returns the header followed by those parameters, or, for a fluent rule, by the conditions rendered in the legacy form.Validator::validateAttribute()calls it only when a check fails. Thevalidate*()methods still receive the header alone, so a plan's conditions are never applied twice.- The header passed in is the one that was validated, so resolved field references such as
[items.0.id]are reported as before. - In a
Validatorsubclass the rule object is not captured as a plan. The conditions read during the check are kept on the validator and reused for the report. If the check failed before reading them (for example a nested array value), they are read once at that point.
Legacy rendering and the string form
- The rendering moved from
DatabaseRule::formatWheres()toDatabaseConditions::toParameters(), which the string form and the failure report share. - Callbacks and
whereIn/whereNotInhave no legacy form and are omitted, as before. - An operand that is an object, such as a query
Expression, cannot be rendered.(string) $rulethrows aLogicExceptionthat names the column. The failure report callstoParameters(omitOpaqueOperands: true)and leaves the operand out.
Condition merging
validateExists()andvalidateUnique()always resolve the parameters after the header throughgetExtraConditions()/getUniqueExtra(), then merge the result with the current rule's conditions through the newDatabaseConditions::merge().- A fluent
uniquerule reaches the shared hook for comparisons and null checks. A rule containing onlywhereIn(),whereNotIn()or callbacks keeps its original query scope. - An independent lookup inside a condition hook, query callback, or error-message callback uses its own parameters. Subclasses can still inspect the rule being validated.
merge()returns either operand unchanged when the other is empty, so the base validator's batched and per-item paths still build identical presence queries.- After nested attribute validation,
$currentRuleagain describes the enclosing check. At the end of a top-level check it is cleared.
Float formatting
Number::toString()usessprintf('%.*h', -1, $number). Precision-1selects PHP's shortest round-trip form without readingprecisionorserialize_precision, and%hignores the numeric locale.
Design Decisions and Trade-offs
- Report at the failure boundary instead of widening the validated parameters. Passing the full list to
validate*()would have required every header reader to tolerate a tail and risked double-applying conditions. - Verbatim parameters for string and array rules, rendered parameters for fluent rules. Verbatim storage reproduces the previous output exactly, including native values in array rules.
- Throw from the string form, omit only in the failure report. A rule string that silently lost a predicate would validate against more rows than the rule declares, so
(string) $rulefails loudly. A failure report must not turn a validation failure into an exception, so it omits the operand. - Laravel's merge order and hook reach. Parameter and hook conditions come first, followed by the rule's own. The shared hook runs for a
uniquerule only when it has extra conditions. - The hook receives no segments for a fluent rule. Typed conditions are not rendered and parsed again, because that would reinterpret literal values such as
NULL. A hook can add conditions to a fluent rule but cannot inspect or rewrite the builder's own. - Keep the database declaration local to its check. The validator passes a builder or compiled plan to the check that owns it. If a subclass calls the parent check twice, each call uses the same declaration. Error reporting uses the conditions that check read.
- Native formatter, no process-wide settings. No custom float formatter was added and no ini value is modified at runtime.
- Accepted limitation. The validation plan cache and presence lookup keys are still built with
serialize(), which followsserialize_precision. A lossy value (1–16) can make rules with close float parameters share a cached plan. This is unchanged, andvalidation.mdkeeps its statement that float conversion relies on PHP's defaultserialize_precision=-1.
Changes
Support
Number::toString(): format finite floats withsprintf('%.*h', -1, ...).
Validation
DatabaseConditions: addtoParameters()andmerge().DatabaseConditionOperator::isMembership()identifiesInandNotIn.DatabaseRulePlan: retain the written extra parameters; addfailureParameters().Rules\DatabaseRule::formatWheres(): delegate toDatabaseConditions::toParameters(), which throws for an operand without a string form.Concerns\ValidatesAttributescombines each check's own conditions with its validator hooks.callReplacer()returns a string. Closure replacers run directly and class-based replacers go throughcallClassBasedReplacer().Validatorreports complete database-rule failure parameters and restores the enclosing rule after a nested check.
Documentation
database.md: PDO float bindings and SQL escaping no longer depend onprecisionorserialize_precision.validation.md: a rule whose condition uses a query expression cannot be converted to a string.
Tests
SupportNumberTest: output ofNumber::toString(), including underserialize_precision17 and 6.ValidationValidatorTest:- failure parameters for string, array, fluent and wildcard rules, an expression operand and a value rejected before any query, in the base validator and a subclass;
- subclasses that add a scope through parameters or either condition hook, including unique rules with no predicates, membership predicates alone, and membership mixed with a comparison;
- a condition hook that validates another attribute and performs a separate database lookup;
- independent database lookups during message selection, attribute formatting, message replacement and an
after()hook.
ValidationExistsRuleTest: the string form rejects a condition with an expression operand.
Validation
Two regression tests failed on 19a1c648b: a message selector missed an existing row, and a nested uniqueness check re-entered the outer condition hook. Both pass with the fix. All 2,172 validation unit tests passed, as did the applicable SQLite batching tests.
Earlier local verification on PHP 8.4.27 with Swoole 6.2.4:
tests/Validation: 2167 tests passed.tests/Integration/Validation: passed on the default test connection (115 tests, 4 skipped) and on MySQL 8.4.11 (115 tests, 1 skipped).tests/Data(2183) andtests/Foundation(1711, 3 skipped): passed.tests/Telescope(516) andSupportNumberTest(28): passed at2dbc667f9, before the last two commits, which only touch the validation package.- Two intermediate commits were tested in isolation from an exported tree:
tests/Validationpassed with 2163 tests atbdcdb7015and 2166 tests at2d75cd09d. - PHPStan on
src/validation/src,src/support/src/Number.phpand the changed test files: no errors. - php-cs-fixer dry run on the changed PHP files: no changes required.
Number::toString()output was compared with the previous implementation over roughly 800,000 floats: identical under default settings, and unchanged underserialize_precision17 and 6 and a comma-decimal locale.- Bound float text,
escape(),toRawSql()andincrement()amounts were identical under five combinations ofprecisionandserialize_precisionon SQLite. - Each problem above, and each automated review finding, was reproduced before the change and confirmed fixed afterwards on in-memory SQLite; the original three were also confirmed on MySQL 8.4.11.
Risks and Review Notes
- Custom message replacers. A validator subclass that overrides the protected
callReplacer()method must declarestringas its return type. Normal replacer registration is unchanged. failed()output grows. Code asserting the header-only output of this branch will see the extra parameters. The new output matches Laravel.- Hooks now apply to fluent rules. Validator subclasses can scope fluent rules through their condition hooks. A fluent unique rule containing only membership predicates still skips the shared hook.
- A scope added through both hooks appears twice. For a
uniquerule with conditions, a subclass that adds the same condition ingetUniqueExtra()andgetExtraConditions()producestenant_id = ? and tenant_id = ?. The equivalent string rule behaves the same way, and the result is unaffected. $currentRuleisnullafter a run. Subclasses that read it insideafter()hooks will no longer see the last validated rule.(string) $rulethrows aLogicExceptionfor expression operands. It previously failed with a generic conversionError, so only the exception type and message change.- Documentation and the recorded plan.
docs/plans/2026-11-15-validation-native-rules.mdsays not to claim independence fromserialize_precision.database.mdnow makes that claim for PDO bindings and SQL escaping only; please confirm this is acceptable. Floats nested inside JSON-cast attributes are encoded byjson_encode()before binding and still follow the setting. - Allocation. The base validator creates one empty
DatabaseConditionsper presence check because the hooks are always called. A 2,999-item comparison against the previous code showed no difference outside measurement noise; it was not a rigorous benchmark. - Review focus.
validateAttribute()supplies the declaration for each database check.getExistCount()andvalidateUnique()take and restore it around the hooks and query.DatabaseConditions::toParameters()renders failure details.
Related Information
- Follow-up to #745, which introduced typed database conditions,
DatabaseRulePlanandNumber::toString(). - Follow-up commits cover nested database checks, unique-rule hook behavior and expression operands in rule strings.
- No issues or follow-up tickets are linked.
[!NOTE]
Fix database rule failure parameters, scoped conditions, and float formatting in Validator
Number::toString now formats finite floats via sprintf('%h') with precision -1, so output is the shortest round-trip form and ignores PHP precision/serialize_precision settings. Non-finite floats still render as NAN, INF, and -INF.
- The validator tracks the database rule dispatched to each check, so
validateUnique and getExistCount combine conditions from the dispatched rule (plan or Unique/Exists builder) with conditions supplied by validation parameters and extra-condition hooks. Nested validation restores the enclosing rule state.
DatabaseRulePlan::failureParameters builds legacy-style parameter lists for failed database rules, preserving legacy extras and rendering typed conditions via DatabaseConditions::toParameters (booleans become integers, floats use Number::toString).
DatabaseRule::formatWheres uses toParameters, and FormatsMessages::callReplacer now always returns a string.
- Risk: converting a database rule to a string throws
LogicException when a condition has a non-membership object operand without a string form; membership predicates no longer trigger the unique-condition hook.
- Behavioral Change: manual database lookups made inside query callbacks or hooks now use their own conditions instead of inheriting the outer rule's conditions.
Macroscope summarized cba4cb2.
Summary by CodeRabbit
- Bug Fixes
- Database validation rules now consistently combine conditions from rule definitions and validation hooks. Failed checks report the appropriate conditions, and nested validation no longer causes conditions to leak between checks.
- Finite floating-point values are now converted consistently regardless of PHP’s precision settings.
- Documentation
- Clarified that finite values are preserved independently of PHP precision settings and that database rules with query expressions cannot be converted to strings.