leknoppix / laravel-filters
Easily add filters to your FormRequests
6.5
2024-10-14 19:20 UTC
Requires
- php: ^7.0|^8.0
- illuminate/http: ^5.5|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/pipeline: ^5.5|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/support: ^5.5|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- laravel/helpers: ^1.3
Requires (Dev)
- orchestra/testbench: ^8.0
- phpunit/phpunit: ^9.0
README
Installation
composer require thibaud-dauce/laravel-filters
Basic Usage
request()->filter([
'email' => ['trim', 'strtolower'],
'name' => ['trim', 'ucfirst'],
])->validate([
'email' => ['required', 'email'],
'name' => ['required', 'string'],
]);
request('email') // trimed and all lowercase
request('name') // trimed and ucfirst
See the ./tests
directory for more examples.
Other possibilities
Native PHP function
$filters = new Filters([
'name' => ['trim', 'strtoupper'],
]);
$data = $filters([
'name' => ' Jane ',
]);
$this->assertEquals([
'name' => 'JANE',
], $data);
Callback
$filters = new Filters([
'name' => ['ucfirst', function($value) {
return trim($value);
}],
]);
$data = $filters([
'name' => ' Jane ',
]);
$this->assertEquals([
'name' => 'Jane',
], $data);
Invokable class
$filters = new Filters([
'name' => ['ucfirst', new class {
public function __invoke($value)
{
return trim($value);
}
}],
]);
$data = $filters([
'name' => ' Jane ',
]);
$this->assertEquals([
'name' => 'Jane',
], $data);
Container resolution
Then MyAwesomeFilter
will be resolved out of the container and the __invoke
method will be called.
$filters = new Filters([
'name' => ['ucfirst', MyAwesomeFilter::class],
]);
FormRequest Usage
Add a filters
method to your FormRequest
:
class MyRequest extend FormRequest {
public function authorized() { return true; }
public function rules() { return []; }
public function filters()
{
return [
'name' => 'trim';
];
}
}
Note that the rules will be checked after the filters.