leknoppix/laravel-filters

Easily add filters to your FormRequests

6.5 2024-10-14 19:20 UTC

This package is not auto-updated.

Last update: 2024-10-29 17:43:55 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.