This is just a list of Laravel's macro found here and there. Feel free to add yours!
Laravel's macroable classes are:
- Illuminate/Support/Arr
- Illuminate/Database/Query/Builder
- Illuminate/Support/Collection
- Illuminate/Filesystem/Filesystem
- Illuminate/Cache/Repository
- Illuminate/Routing/Router
- Illuminate/Http/Request
- Illuminate/Routing/ResponseFactory
- Illuminate/Support/Str
- Illuminate/Http/UploadedFile
- Illuminate/Routing/UrlGenerator
Collection::macro('countRecursive', function () {
return count($this->items, COUNT_RECURSIVE);
});
by krzystof
Pipe (added in core, see PR)
Apply any given function to the collection
Collection::macro('pipe', function ($callback) {
return $callback($this);
});
Source adamwathan's book
Given a collection of pairs, turn it into a key => value collection
Collection::macro('toAssoc', function () {
return $this->reduce(function ($items, $pair) {
list($key, $value) = $pair;
return $items->put($key, $value);
}, new static);
});
Source: adamwathan
Collection::macro('transpose', function () {
$items = array_map(function (...$items) {
return $items;
}, ...$this->values());
return new static($items);
});
Source: adamwathan
Check if a file or directory is writable by all users
Filesystem::macro('isWritableByAll', function ($filepath) {
return file_exists($path) && substr(sprintf('%o', fileperms($path)), -1) === '7';
});
by krzystof
Change permissions on a file or directory to be writable by all users
Filesystem::macro('makeWritableByAll', function ($filepath) {
return chmod($path, 0777);
});
by krzystof
Get only the parameters of the request if they are not empty
Request::macro('filterOnly', function (...$attributes) {
return array_filter($this->only($attributes));
});
echo $request->title;
// ''
echo $request->content;
// 'something'
$request->only('title', 'content');
// ['title' => '', content' => 'something']
$request->filterOnly('title', 'content');
// ['content' => 'something']
by krzystof