PHPackages                             lphilippo/laravel-castable-form-request - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. lphilippo/laravel-castable-form-request

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

lphilippo/laravel-castable-form-request
=======================================

Laravel/Lumen package to add Eloquent-like casts to Form Requests.

0.3.3(2y ago)826.8k↓41.3%2[1 PRs](https://github.com/lphilippo/laravel-castable-form-request/pulls)MITPHPPHP &gt;= 7.4

Since Aug 29Pushed 2y ago1 watchersCompare

[ Source](https://github.com/lphilippo/laravel-castable-form-request)[ Packagist](https://packagist.org/packages/lphilippo/laravel-castable-form-request)[ RSS](/packages/lphilippo-laravel-castable-form-request/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (15)Used By (0)

[![Test Suite Status](https://github.com/lphilippo/laravel-castable-form-request/workflows/Test%20Suite/badge.svg)](https://github.com/lphilippo/laravel-castable-form-request)[![Total Downloads](https://camo.githubusercontent.com/c29655e78e608a29a9be33d9adeebbb20b73d38978d5028af2b3d1354951ca2f/68747470733a2f2f706f7365722e707567782e6f72672f6c7068696c6970706f2f6c61726176656c2d6361737461626c652d666f726d2d726571756573742f642f746f74616c2e737667)](https://packagist.org/packages/lphilippo/laravel-castable-form-request)[![Latest Stable Version](https://camo.githubusercontent.com/942d0fa2b63743079eb36f326aacb393d781b6581ec979917c640c2cc78e92ad/68747470733a2f2f706f7365722e707567782e6f72672f6c7068696c6970706f2f6c61726176656c2d6361737461626c652d666f726d2d726571756573742f762f737461626c652e737667)](https://packagist.org/packages/lphilippo/laravel-castable-form-request)[![License](https://camo.githubusercontent.com/c9179ac18c390942bd27b0be763514e6d021f20f6cdb3a1c908360f095eb0eb6/68747470733a2f2f706f7365722e707567782e6f72672f6c7068696c6970706f2f6c61726176656c2d6361737461626c652d666f726d2d726571756573742f6c6963656e73652e737667)](https://github.com/lphilippo/laravel-castable-form-request)

First of all, you can now use Laravel-like form-requests within Lumen. Additionally you can extend your FormRequests with default values and (nested!) casting, to have full control over the data that enters your application. It's important to note that also for nested array, validation rules are required for each property, as otherwise the property will be omitted from the sanitised result.

The `defaults()` are combined with the data source of the request prior to validation, whereas the `casts()` are being applied once validation is succesfull. By enforcing this order, the casts can be used to control in which type the data is provided to the application, regardless of the validation of the user data. This is especially usefull for working with `Carbon` dates internally.

There is no distinction made between the various input sources of the request, similar to the standard implemenation of FormRequest in Laravel [Illuminate/Foundation/Http/FormRequest](https://laravel.com/api/7.x/Illuminate/Foundation/Http/FormRequest.html).

Installation
------------

[](#installation)

```
composer require lphilippo/laravel-castable-form-request
```

Configuration for Lumen
-----------------------

[](#configuration-for-lumen)

To use the form-requests in Lumen, you will only need to register the service provider in `bootstrap/app.php`.

```
$app->register(LPhilippo\CastableFormRequest\ServiceProvider::class);
```

Usage in Lumen
--------------

[](#usage-in-lumen)

Simply extend your own form-request from `LPhilippo\CastableFormRequest\Http\Requests\LumenFormRequest` and add the rules, casts and defaults that you need.

Usage in Laravel
----------------

[](#usage-in-laravel)

As the `FormRequest` of this package should not be used over the standard one of Laravel (unless you have no need for the redirect actions), all functionality can still be achieved with a bit more code.

The `FormRequest` simply extends the base class and adds the `LPhilippo\CastableFormRequest\Casting\CastsWhenValidatedTrait`. This will allow the `casts()` to be applied, but in order to make use of the `defaults()` as well, please add the following code to your class:

```
    /**
     * Allow default values through filtering before validation.
     *
     * @return array
     */
    public function prepareForValidation()
    {
        return $this->replace(
            array_merge(
                $this->defaults(),
                $this->all()
            )
        );
    }
```

Full FormRequest example:
-------------------------

[](#full-formrequest-example)

A full example that uses the validation, the casts and the default values within the same implementation, would be:

```
use LPhilippo\CastableFormRequest\Http\Requests\FormRequest;

class ProductRequest extends FormRequest
{
    /**
     * @inheritdoc
     */
    public function defaults()
    {
        return [
           'id' => 1,
       ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
           'created_at' => 'required|date_format:Y-m-d',
           'id' => 'required|integer',
       ];
    }

    /**
     * @inheritdoc
     */
    public function casts()
    {
        return [
           'created_at' => 'datetime',
           'id' => 'integer',
       ];
    }
}
```

In your controller you can then access either the validated uncasted data:

```
$request->validated();
```

Or the fully sanitised data, which is prepared for further internal processing.

```
$request->sanitised();
```

Please note that `sanitised` does not include properties that are not validated. This also applies for nested arrays, which will be stripped from properties without validation.

Nested validation rules
-----------------------

[](#nested-validation-rules)

Similar to standard validation rules, also casting rules can be nested. For example, the following rules are valid. Please keep in mind that casting rules should always work alongside validation rules (which are applied first), as otherwise the outcome of the casts could be unexpected.

```
    /**
     * @inheritdoc
     */
    public function casts()
    {
        return [
            'products' => 'array',
            'products.*' => 'array',
            'products.*.id' => 'int',
            'products.*.category_id' => 'array',
            'products.*.category_id.*' => 'int',
    }
```

Although this can be written shorter by only defining the dot notation, as the array rules will be implied already:

```
    /**
     * @inheritdoc
     */
    public function casts()
    {
        return [
            'products.*.id' => 'int',
            'products.*.category_id.*' => 'int',
    }
```

Nested default values
---------------------

[](#nested-default-values)

The same nested approach can be applied to default values. However, it needs to be pointed out that nested array defaults are only applied when the resulting `validated` content, contains the array in the first place. It will not initialize the array in question.

```
    /**
     * @inheritdoc
     */
    public function casts()
    {
        return [
            'status' => 'pending',
            'products.*.status' => 'available',
            'provider.country.currency' => 'EUR',
    }
```

Adding custom validator rules
-----------------------------

[](#adding-custom-validator-rules)

In certain use cases, specifying all validation rules in the `$rules` variable is not enough. For example, if based on the request route, more tailored validation is needed, this can be achieved with adding something along the following structure:

```
    /**
     * @inheritdoc
     */
    public function withValidator($validator)
    {
        $entityId = $this->route('id');

        if ($entityId === 1) {
            $validator->addRules([
                'key' => 'required|string|in:' . implode(',', self::RESTRICTED_KEYS),
            ]);
        }
    }
```

Important limitations (by design)
---------------------------------

[](#important-limitations-by-design)

Because the primary purpose of this package is to validate any input that is entering the system, the validation rules are always leading. Unfortunately, when you specify any validation rule on an array (per standard Laravel behavior), the elements of the array are no longer filtered when calling `Validator::validated`.

As this goes contrary our purpose, this functionality is disabled, which allows us to define each array element. The downside is that empty arrays that might exist in the original data, will *not* be present in the result of `sanitised`.

Although possible, at this moment it's not considered in scope.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~123 days

Recently: every ~61 days

Total

10

Last Release

978d ago

PHP version history (4 changes)0.1.0PHP &gt;=7.1

0.2.0PHP ^7.3|^8.0

0.3.0PHP ^8.0.2

0.3.2PHP &gt;= 7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/4935b95d92a3bba2ddd1960d9859f4f700df230c6f03146f7761c572d8a5b807?d=identicon)[lphilippo](/maintainers/lphilippo)

---

Top Contributors

[![lphilippo](https://avatars.githubusercontent.com/u/732984?v=4)](https://github.com/lphilippo "lphilippo (36 commits)")[![misakstvanu](https://avatars.githubusercontent.com/u/42741294?v=4)](https://github.com/misakstvanu "misakstvanu (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/lphilippo-laravel-castable-form-request/health.svg)

```
[![Health](https://phpackages.com/badges/lphilippo-laravel-castable-form-request/health.svg)](https://phpackages.com/packages/lphilippo-laravel-castable-form-request)
```

###  Alternatives

[spatie/laravel-honeypot

Preventing spam submitted through forms

1.6k6.0M60](/packages/spatie-laravel-honeypot)[propaganistas/laravel-phone

Adds phone number functionality to Laravel based on Google's libphonenumber API.

3.0k35.7M107](/packages/propaganistas-laravel-phone)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

759569.4k13](/packages/wendelladriel-laravel-validated-dto)[axlon/laravel-postal-code-validation

Worldwide postal code validation for Laravel and Lumen

3853.3M1](/packages/axlon-laravel-postal-code-validation)[sunspikes/clamav-validator

Custom Laravel 5 anti-virus validator for file uploads.

3651.8M3](/packages/sunspikes-clamav-validator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
