thibaud-dauce/laravel-filters

Easily add filters to your FormRequests

6.5.0 2023-02-28 07:16 UTC

This package is auto-updated.

Last update: 2024-11-28 10:53:49 UTC


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.