Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Last active February 26, 2023 14:20
Show Gist options
  • Save adamwathan/610a9818382900daac6d6ecdf75a109b to your computer and use it in GitHub Desktop.
Save adamwathan/610a9818382900daac6d6ecdf75a109b to your computer and use it in GitHub Desktop.
Request filtering macros

Empty strings to null

Simple macro for converting empty strings to null:

Request::macro('nullable', function ($key) {
    return $this->input($key) == '' ? null : $this->input($key);
});

Use like:

$post = Post::create([
    'description' => request()->nullable('description'),
    // ...
]);

Filter through arbitrary functions

Allows you to trim things, lowercase things, whatever you want. Pass a callable or array of callables that each expect a single argument:

Request::macro('filter', function ($key, $filters) {
    return collect($filters)->reduce(function ($filtered, $filter) {
        return $filter($filtered);
    }, $this->input($key));
});

Use like:

// Just trim
User::create([
    'email' => request()->filter('email', 'trim'),
    // ...
]);

// Trim and lowercase
User::create([
    'email' => request()->filter('email', ['trim', 'strtolower']),
    // ...
]);

Filter through arbitrary functions, with nullable baked in as a bonus

This essentially registers nullable as an additional filter, and reimplements the nullable macro in terms of filter:

Request::macro('filter', function ($key, $filters) {
    return collect($filters)->reduce(function ($filtered, $filter) {
        return collect([
            'nullable' => function ($value) {
                return $value == '' ? null : $value;
            }
        ])->get($filter, function () use ($filter) {
            return $filter; 
        })($filtered);
    }, $this->input($key));
});

Request::macro('nullable', function ($key) {
    return $this->filter($key, 'nullable');
});

Now nullable is available as a possible filter:

Post::create([
    'description' => request()->filter('description', ['trim', 'nullable']),
    // ...
]);
@reinink
Copy link

reinink commented Dec 4, 2016

Love it Adam. I'm inclined to set a default on $filters just so you don't have to switch to request()->get() in those situations where you're not filtering. But maybe that's weird?

Request::macro('filter', function ($key, $filters = []) {
    return collect($filters)->reduce(function ($filtered, $filter) {
        return $filter($filtered);
    }, $this->input($key));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment