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'),
// ...
]);
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']),
// ...
]);
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']),
// ...
]);
Love it Adam. I'm inclined to set a default on
$filters
just so you don't have to switch torequest()->get()
in those situations where you're not filtering. But maybe that's weird?