guerrilla / laravel-request-filters
Simple & lean request filtering for Laravel 5.6+
Requires
- php: ^7.0 || ^8.0
- illuminate/contracts: ^5.6|~6.0|~7.0|^8.0
- illuminate/support: ^5.6|~6.0|~7.0|^8.0
Requires (Dev)
- phpunit/phpunit: ~6.0|~7.0|~8.0|^9.0
This package is auto-updated.
Last update: 2024-09-06 04:44:31 UTC
README
About
Laravel provides tools to validate HTTP requests allowing developers to ensure the input data is in the correct structure.
This package provides tools to filter the valid data into the format intended.
It feels like it is part of the Laravel framework and couldn't be any simpler to use.
Requirements
Laravel 5.6+
Features
- Format input with a collection of pre-made and tested Filters
FilterRequests
trait that easily plugs into aFormRequest
and enable filteringInputFilter
that allows developers to easily implement their own filtersRequestFiltering
tool that can apply the same filters to any string you pass in- Nested AND array filtering just like Laravel's own validator 👌
- String based filtering similar to Laravel's validator + custom parsable filters
Included Filters
Included Filters (as string literals)
You can make your own custom filters by implementing the FilterInterface
:)
How to use
Import via composer:
composer require guerrilla/laravel-request-filters
In your FormRequest use the following trait:
use Guerrilla\RequestFilters\FilterRequests
Describe your filters (Laravel rules included for familiarisation):
public function rules():array { return [ 'email' => ['required', 'email', 'bail'], 'name' => ['required'], 'employees.*.name' =>['required'] ]; }
public function filters():array { return [ 'email' => [new FilterTrim, new FilterSanitizeEmail], 'name' => [new FilterTrim, new FilterSanitizeText, new FilterCapitalize], 'employees.*.name' => [new FilterCapitalize], 'date' => [new FilterTrim, new FilterDate('d/m/Y')] ]; }
Or use the string based syntax:
public function filters():array { return [ 'email' => 'trim|email', 'name' => 'trim|sanitize|capitalize', 'employees.*.name' => 'capitalize', 'date' => 'trim|date:d/m/Y' ]; }
Validate the request as per normal but, the results will be now filtered :)
$input = $request->validated(); echo $input['email']; //trimmed and sanitized email!
You can optionally just run the filter on any string you like outside of the request:
$validated_input = $request->validate([...]); $filtered_result = InputFilter::filter( $validated_input, [ 'email' => [new FilterTrim], 'name' => [new FilterTrim], 'meta.*.attributes' => [new MyCustom1Filter(1), new MyCustom2Filter(2)] ] );
Using your own custom filtering rules to the string parsing syntax is easy!
$validated_input = $request->validate([...]); $custom_filters = [ 'custom1' => MyCustom1Filter::class, 'custom2' => MyCustom2Filter::class ]; $filtered_result = InputFilter::filterFromString( $validated_input, [ 'email' => 'trim', 'name' => 'trim', 'meta.*.attributes' => 'custom1:1|custom2:2' ], $custom_filters );