spatie/piper
Pipe-operator-first PHP utility library for array and string manipulation. Piper ports many Laravel Collection and Str helpers to standalone functions that work with primitives, so you can compose readable pipelines for filtering, mapping, joining, and more.
composer require spatie/piper
use function Spatie\Piper\Arr\{filter, map};
use function Spatie\Piper\Str\{lower, replace};
$result = [1, 2, 3, 4, 5]
|> filter(fn ($n) => $n % 2 === 0)
|> map(fn ($n) => "Item $n")
|> join(', ');
// "Item 2, Item 4"
[1, 2, 3] |> ... |> suffix('.')).Spatie\Piper\Arr (arrays) and Spatie\Piper\Str (strings).Data Transformation Pipelines:
$users = User::all()
|> map(fn ($user) => $user->name)
|> filter(fn ($name) => strlen($name) > 5)
|> sort();
String Manipulation:
$path = 'app/Models/User'
|> afterLast('/')
|> studly();
// "User" (class name extraction)
Validation Helpers:
$email = 'test@example.com'
|> is('*@*.com')
|> tap(fn ($isValid) => $isValid || abort(422, 'Invalid email'));
collect()->pipe() with Piper’s primitives for lightweight operations.fn (Post $post) => ...) for IDE autocompletion.Arr and Str functions seamlessly (e.g., ['a', 'b'] |> join(', ') |> upper()).| Use Case | Pattern |
|---|---|
| Filtering | `$array |
| Mapping | `$array |
| String Formatting | `$str |
| Conditional Logic | `$value |
| Data Extraction | `$path |
Mutable Operations:
$arr = $arr |> push() is safe, but $arr[] = ... breaks pipelines).tap() for side effects:
$arr |> tap(fn ($a) => $a[] = 'new');
Empty Inputs:
explode() or map() may return null or empty arrays/strings.default() or isNotEmpty():
$str |> explode(',') |> default([]) |> count();
Regex Caveats:
isMatch() and matchAll() use PCRE; escape special chars:
$str |> is('/\d+/'); // Fails if $str contains literal '/'
// Fix: Use `preg_quote()` or raw strings.
Performance:
map() + filter() + sort()). Use intermediate variables if needed.$result = $data
|> tap(fn ($d) => logger()->debug('Debug:', ['data' => $d]))
|> map(...);
$empty = [] |> filter(fn ($x) => false); // Returns []
$null = null |> default('fallback'); // Returns 'fallback'
Custom Functions:
Add to composer.json autoload:
// app/Helpers/Piper.php
use function Spatie\Piper\Arr\{*};
function customFn($arr) { ... }
Then import globally in composer.json:
"autoload": {
"files": ["app/Helpers/Piper.php"]
}
Alias Existing Functions:
use function Spatie\Piper\Str\{upper as toUpper};
Laravel Service Provider:
Register global functions in AppServiceProvider:
use function Spatie\Piper\Arr\{*};
use function Spatie\Piper\Str\{*};
lower()) respect PHP’s locale settings. Set via setlocale() if needed.$query = User::query()
|> where('active', true)
|> orderBy('name')
|> get()
|> map(fn ($user) => $user->email);
$result = $data
|> filter(fn ($x) => $x > 0)
|> map(fn ($x) => $x * 2)
|> sum();
$transform = fn ($str) => $str
|> trim()
|> lower()
|> kebab();
How can I help you explore Laravel packages today?