VOOZH about

URL: https://deepwiki.com/hypervel/foundation/4.3-form-request-validation

⇱ Form Request Validation | hypervel/foundation | DeepWiki


Loading...
Last indexed: 7 February 2026 (101eff)
Menu

Form Request Validation

Purpose and Scope

This document covers the FormRequestServiceProvider, which integrates form request validation with the dependency injection system. The provider registers a callback with RouteDependency that automatically triggers validation for any class implementing the ValidatesWhenResolved interface when resolved from the container. This enables automatic validation of form requests before they reach controller methods, without requiring explicit validation calls.

For general HTTP request lifecycle information, see HTTP Kernel and Request Lifecycle. For exception handling related to validation failures, see Exception Handling and Error Responses.


FormRequestServiceProvider Architecture

The FormRequestServiceProvider serves as the integration point between the dependency injection system and form request validation. It registers a single callback during the boot phase that monitors all resolved dependencies and triggers validation when appropriate.

Provider Architecture


Sources: src/Providers/FormRequestServiceProvider.php1-24


FormRequestServiceProvider Implementation

The FormRequestServiceProvider class is minimal by design, consisting of a single boot() method that establishes the validation integration.

Provider Boot Process


The callback registered is: function (ValidatesWhenResolved $request) { $request->validateResolved(); }. This closure is invoked by the RouteDependency class whenever an instance implementing ValidatesWhenResolved is resolved from the container.

Sources: src/Providers/FormRequestServiceProvider.php11-22


ValidatesWhenResolved Interface

The ValidatesWhenResolved interface is the contract that signals to the dependency injection system that an object should be validated upon resolution. Any class implementing this interface will have its validateResolved() method automatically called by the FormRequestServiceProvider.

Interface Integration with DI System


The interface itself does not define the validation logic—it only provides the contract. The actual implementation is typically provided by the ValidatesWhenResolvedTrait, which is used by the FormRequest class.

Sources: src/Providers/FormRequestServiceProvider.php9 src/Providers/FormRequestServiceProvider.php19-20


Dependency Injection Integration

The integration between form request validation and the dependency injection system occurs through the RouteDependency class from the hypervel/http package. This class provides lifecycle hooks that allow the FormRequestServiceProvider to intercept dependency resolution.

DI Resolution and Validation Trigger


This integration ensures that validation occurs transparently during dependency resolution, before the controller method executes. Developers simply type-hint FormRequest subclasses in their controller methods, and validation is handled automatically.

Sources: src/Providers/FormRequestServiceProvider.php18-21


Validation Lifecycle

When a FormRequest is resolved from the container, the validation lifecycle executes automatically through the ValidatesWhenResolvedTrait. The process follows a specific sequence to ensure authorization and validation occur before the request reaches the controller.

Validation Execution Flow


The validator instance is cached in the coroutine context using a key based on the object hash, ensuring each request maintains its own validator state. This caching prevents redundant validator creation when accessing validation results multiple times.

Sources: src/Providers/FormRequestServiceProvider.php19-20


FormRequest Class Overview

While the FormRequestServiceProvider handles the integration with dependency injection, the actual validation logic resides in the FormRequest class and its associated traits. FormRequest subclasses define validation behavior through several overridable methods.

Core Validation Methods

MethodReturn TypePurposeDefault Behavior
rules()arrayDefine validation rulesReturns empty array
authorize()boolDetermine if user is authorizedReturns false
messages()arrayCustom error messagesReturns empty array
attributes()arrayCustom attribute namesReturns empty array
validator(ValidationFactory $factory)ValidatorCustomize validator creationNot defined by default
withValidator(Validator $validator)voidConfigure validator after creationNot defined by default
prepareForValidation()voidModify input before validationNot defined by default

The FormRequest class implements ValidatesWhenResolved and uses the ValidatesWhenResolvedTrait to provide the validateResolved() method, which is the entry point called by the FormRequestServiceProvider.

Validator Instance Creation


The validator is cached in the coroutine context using a key format of {object_hash}:validator, ensuring each FormRequest instance maintains its own validator state throughout the request lifecycle.

Sources: src/Providers/FormRequestServiceProvider.php19-20


Authorization and Error Handling

The authorization system executes before validation, determining whether the current user can make the request. If authorization fails, an AuthorizationException is thrown and validation never occurs.

Authorization Check Flow


By default, passesAuthorization() returns false unless the authorize() method is explicitly defined and returns true. This fail-secure design ensures requests are denied unless authorization is explicitly granted.

Validation Error Handling

When validation fails, the failedValidation() method is called, which throws a ValidationException containing the validator instance and a prepared response. The response is created by the response() method, which returns a 422 status by default.


The $errorBag property specifies which error bag to use (default: 'default'), while the $dontFlash property defines input keys that should not be flashed to the session on redirect (default: ['password', 'password_confirmation']).

Sources: src/Providers/FormRequestServiceProvider.php19-20 </old_str>

<old_str>

Input Casting System

The HasCasts trait provides a comprehensive type casting system that transforms raw request input into strongly-typed PHP values. The casting system supports primitive types, collections, dates, enums, data objects, and custom casters.

Casting Overview


Sources: src/Http/Traits/HasCasts.php20-25 src/Http/Traits/HasCasts.php67-85 src/Http/Traits/HasCasts.php90-111


Primitive Cast Types

The framework supports 18 primitive cast types for common data transformations. These types handle null values gracefully and provide consistent conversion behavior.

Primitive Cast Type Reference

Cast TypePHP TypeBehaviorNull Handling
int, integerintCast to integerReturns null
real, float, doublefloatCast to float, handles Infinity/NaNReturns null
decimal:XstringFormat as decimal with X digitsReturns null
stringstringCast to stringReturns null
bool, booleanboolCast to booleanReturns null
arrayarrayJSON decode to arrayReturns null
jsonarrayJSON decode to arrayReturns null
objectobjectJSON decode to objectReturns null
collectionCollectionJSON decode wrapped in CollectionReturns null
dateCarbonInterfaceParse as date (00:00:00)Returns null
datetimeCarbonInterfaceParse as datetimeReturns null
custom_datetimeCarbonInterfaceParse as datetime (custom format)Returns null
timestampintParse and convert to Unix timestampReturns null

Sources: src/Http/Traits/HasCasts.php42-60 src/Http/Traits/HasCasts.php116-154

Special Float Handling

The fromFloat() method handles special IEEE 754 float values:


Sources: src/Http/Traits/HasCasts.php393-401


DateTime Casting

The datetime casting system provides flexible parsing of various date/time formats using Carbon. It handles Carbon instances, DateTime objects, Unix timestamps, standard date formats, and custom formats.

DateTime Parsing Flow


The $dateFormat property defines the format for date/datetime casts, defaulting to 'Y-m-d H:i:s.u' (includes microseconds).

Sources: src/Http/Traits/HasCasts.php34-35 src/Http/Traits/HasCasts.php453-496 src/Http/Traits/HasCasts.php445-448 src/Http/Traits/HasCasts.php509-512


Enum Casting

The system supports casting input values to PHP 8.1+ enum instances, including both UnitEnum and BackedEnum types. The EnumCollector from Hyperf handles the value-to-case resolution.

Enum Cast Process


Sources: src/Http/Traits/HasCasts.php157-159 src/Http/Traits/HasCasts.php311-326 src/Http/Traits/HasCasts.php200-213 src/Http/Traits/HasCasts.php243-246


DataObject Casting

The system supports casting array input to DataObject instances, which provide structured, type-safe data containers. A DataObject class must implement a static make(array $data) method.

DataObject Cast Implementation


Sources: src/Http/Traits/HasCasts.php331-346 src/Http/Traits/HasCasts.php218-238


Custom Cast Classes

The casting system supports custom cast implementations through the CastInputs interface. Custom casters can implement bidirectional transformation logic (get and set operations).

Custom Cast Architecture


Cast Definition Syntax

Custom casts can be defined with arguments using colon and comma separators:

  • Simple: 'field' => CustomCast::class
  • With single argument: 'field' => CustomCast::class . ':argument'
  • With multiple arguments: 'field' => CustomCast::class . ':arg1,arg2,arg3'
  • Using Castable: 'field' => AsDataObjectCollection::of(ItemClass::class)

Sources: src/Http/Traits/HasCasts.php351-372 src/Http/Traits/HasCasts.php374-380


AsDataObjectCollection Cast

The AsDataObjectCollection cast provides collection-based DataObject transformation, converting arrays of arrays into collections of DataObject instances.

AsDataObjectCollection Implementation


Sources: src/Http/Casts/AsDataObjectCollection.php1-76


Class Cast Caching

Custom class casts cache their results to avoid repeated object instantiation when the same field is accessed multiple times. The cache key includes whether validated or raw input was used.


The $classCastCache property stores cached instances to optimize performance when accessing cast values multiple times within a single request.

Sources: src/Http/Traits/HasCasts.php29-30 src/Http/Traits/HasCasts.php177-195


Validation Data Access

FormRequest provides methods to access validation results and retrieve casted values from either validated or raw input.

Data Access Methods

MethodParametersReturnsDescription
validated()NonearrayReturns validated data from validator
casted(?string $key, bool $validate)Key(s), validate flagmixedReturns casted value(s)
all()NonearrayReturns all raw input data

The casted() method provides flexible access to cast values:


Sources: src/Http/FormRequest.php69-72 src/Http/Traits/HasCasts.php67-85


Error Handling and Response

When validation or authorization fails, the FormRequest system throws specific exceptions that are handled by the Exception Handler.

Failure Response Flow


Error Bag and Flash Data

The FormRequest defines properties that control error handling behavior:

  • $errorBag: Specifies the error bag name (default: 'default')
  • $dontFlash: Array of input keys that should not be flashed to the session on redirect (default: ['password', 'password_confirmation'])

Sources: src/Http/FormRequest.php28-39 src/Http/FormRequest.php62-64 src/Http/FormRequest.php145-148 src/Http/FormRequest.php173-176


Complete Cast Type Resolution

The following diagram shows the complete cast type resolution process, including all supported cast types and their resolution priority.


Sources: src/Http/Traits/HasCasts.php116-172


Input Casting System

The HasCasts trait provides a comprehensive type casting system that transforms raw request input into strongly-typed PHP values. The casting system supports primitive types, collections, dates, enums, data objects, and custom casters.

Casting Overview


Sources: src/Http/Traits/HasCasts.php20-25 src/Http/Traits/HasCasts.php67-85 src/Http/Traits/HasCasts.php90-111


Primitive Cast Types

The framework supports 18 primitive cast types for common data transformations. These types handle null values gracefully and provide consistent conversion behavior.

Primitive Cast Type Reference

Cast TypePHP TypeBehaviorNull Handling
int, integerintCast to integerReturns null
real, float, doublefloatCast to float, handles Infinity/NaNReturns null
decimal:XstringFormat as decimal with X digitsReturns null
stringstringCast to stringReturns null
bool, booleanboolCast to booleanReturns null
arrayarrayJSON decode to arrayReturns null
jsonarrayJSON decode to arrayReturns null
objectobjectJSON decode to objectReturns null
collectionCollectionJSON decode wrapped in CollectionReturns null
dateCarbonInterfaceParse as date (00:00:00)Returns null
datetimeCarbonInterfaceParse as datetimeReturns null
custom_datetimeCarbonInterfaceParse as datetime (custom format)Returns null
timestampintParse and convert to Unix timestampReturns null

Sources: src/Http/Traits/HasCasts.php42-60 src/Http/Traits/HasCasts.php116-154

Special Float Handling

The fromFloat() method handles special IEEE 754 float values:


Sources: src/Http/Traits/HasCasts.php393-401


DateTime Casting

The datetime casting system provides flexible parsing of various date/time formats using Carbon. It handles Carbon instances, DateTime objects, Unix timestamps, standard date formats, and custom formats.

DateTime Parsing Flow


The $dateFormat property defines the format for date/datetime casts, defaulting to 'Y-m-d H:i:s.u' (includes microseconds).

Sources: src/Http/Traits/HasCasts.php34-35 src/Http/Traits/HasCasts.php453-496 src/Http/Traits/HasCasts.php445-448 src/Http/Traits/HasCasts.php509-512


Enum Casting

The system supports casting input values to PHP 8.1+ enum instances, including both UnitEnum and BackedEnum types. The EnumCollector from Hyperf handles the value-to-case resolution.

Enum Cast Process


Sources: src/Http/Traits/HasCasts.php157-159 src/Http/Traits/HasCasts.php311-326 src/Http/Traits/HasCasts.php200-213 src/Http/Traits/HasCasts.php243-246


DataObject Casting

The system supports casting array input to DataObject instances, which provide structured, type-safe data containers. A DataObject class must implement a static make(array $data) method.

DataObject Cast Implementation


Sources: src/Http/Traits/HasCasts.php331-346 src/Http/Traits/HasCasts.php218-238


Custom Cast Classes

The casting system supports custom cast implementations through the CastInputs interface. Custom casters can implement bidirectional transformation logic (get and set operations).

Custom Cast Architecture


Cast Definition Syntax

Custom casts can be defined with arguments using colon and comma separators:

  • Simple: 'field' => CustomCast::class
  • With single argument: 'field' => CustomCast::class . ':argument'
  • With multiple arguments: 'field' => CustomCast::class . ':arg1,arg2,arg3'
  • Using Castable: 'field' => AsDataObjectCollection::of(ItemClass::class)

Sources: src/Http/Traits/HasCasts.php351-372 src/Http/Traits/HasCasts.php374-380


AsDataObjectCollection Cast

The AsDataObjectCollection cast provides collection-based DataObject transformation, converting arrays of arrays into collections of DataObject instances.

AsDataObjectCollection Implementation


Sources: src/Http/Casts/AsDataObjectCollection.php1-76


Class Cast Caching

Custom class casts cache their results to avoid repeated object instantiation when the same field is accessed multiple times. The cache key includes whether validated or raw input was used.


The $classCastCache property stores cached instances to optimize performance when accessing cast values multiple times within a single request.

Sources: src/Http/Traits/HasCasts.php29-30 src/Http/Traits/HasCasts.php177-195


Validation Data Access

FormRequest provides methods to access validation results and retrieve casted values from either validated or raw input.

Data Access Methods

MethodParametersReturnsDescription
validated()NonearrayReturns validated data from validator
casted(?string $key, bool $validate)Key(s), validate flagmixedReturns casted value(s)
all()NonearrayReturns all raw input data

The casted() method provides flexible access to cast values:


Sources: src/Http/FormRequest.php69-72 src/Http/Traits/HasCasts.php67-85


Error Handling and Response

When validation or authorization fails, the FormRequest system throws specific exceptions that are handled by the Exception Handler.

Failure Response Flow


Error Bag and Flash Data

The FormRequest defines properties that control error handling behavior:

  • $errorBag: Specifies the error bag name (default: 'default')
  • $dontFlash: Array of input keys that should not be flashed to the session on redirect (default: ['password', 'password_confirmation'])

Sources: src/Http/FormRequest.php28-39 src/Http/FormRequest.php62-64 src/Http/FormRequest.php145-148 src/Http/FormRequest.php173-176


Complete Cast Type Resolution

The following diagram shows the complete cast type resolution process, including all supported cast types and their resolution priority.


Sources: src/Http/Traits/HasCasts.php116-172

Refresh this wiki

On this page