Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Any Laravel Package

nunomaduro/laravel-any

Nuno Maduro's tiny Laravel helper that resolves any class through the service container, automatically injecting its dependencies so you can instantiate objects with zero boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

Verify the gap before you install anything. The package's shipped capability is a single Collection::any(callable): bool macro that short-circuits on the first item passing the truth test. Laravel 9+ ships this natively, so the first command you run is a capability probe, not composer require:

php artisan tinker --execute="var_dump(method_exists(Illuminate\Support\Collection::class, 'any'));"
composer show laravel/framework | grep -i versions

true means stop — you already have the behaviour and adding the package gives you two competing registrations of the same method name.

Install (pre-Laravel 9 only).

composer require nunomaduro/laravel-any

There is no config file, no published assets, no env vars. On Laravel 5.5+ the service provider is auto-discovered. Confirm it actually booted in a real application context rather than assuming discovery worked:

php artisan tinker --execute="var_dump(collect([1])->any(fn (\$i) => \$i === 1));"

Where to look first — the provider, not the README. Read the Collection::macro('any', ...) call and answer exactly two questions before you write a single call site:

  1. Does the truth test compare with === or ==?
  2. Does it accept a key/value pair as well as a closure?

Everything else in this assessment follows from those two lines. Note also that the package's prose description talks about targeting "any supported Laravel version" from one project — that framing does not match the shipped macro. Trust the code, not the blurb.

First real use case: a guard clause. The idiom reads like English and terminates on the first hit:

// Before
$hasExpired = false;
foreach ($invoices as $invoice) {
    if ($invoice->isExpired()) { $hasExpired = true; break; }
}

// After
if ($invoices->any(fn (Invoice $i) => $i->isExpired())) {
    throw new InvoiceExpiredException();
}

If that is the only shape you ever write, $invoices->contains(fn ($i) => $i->isExpired()) is behaviourally identical with zero dependencies. Adopt the package only when the team has formally standardised on the any() name.

Implementation Patterns

Domain guards and validation. The highest-value pattern because it short-circuits and names the intent:

if ($order->lines->any(fn ($line) => $line->quantity > $line->stock)) {
    throw new InsufficientStockException($order);
}

Terminating a pipeline. any() reads best at the end of a filter/map chain, which is where it genuinely beats contains() for clarity:

$blocked = $users
    ->filter(fn ($u) => $u->isActive())
    ->any(fn ($u) => $u->hasFlag('suspended'));

Eloquent collections. Illuminate\Database\Eloquent\Collection extends the base collection, so the macro is inherited with no wiring. Just be aware you are iterating rows already fetched — see the query trap below.

$tenant->subscriptions()->get()->any(fn ($s) => $s->endsWithinDays(7));

Policies and form requests. Pure boolean gates over already-loaded data are the strongest legitimate fit:

public function approve(User $user, Order $order): bool
{
    return $user->roles->any(fn ($role) => $role->can('approve-orders'))
        || $order->total < 100;
}

Test assertions where the failure message matters. Prefer any() over assertTrue($collection->contains(...)) when the intent should be legible in CI output:

$this->assertTrue(
    collect($response->json('items'))->any(fn ($i) => $i['status'] === 'failed'),
    'Expected at least one failed item in the payload.'
);

Normalise at the boundary so removal is a one-file change. Wrap the call once; when you upgrade and delete the package, you swap the body and nothing else moves:

// app/Support/Collections.php
final class Collections
{
    public static function any(iterable $items, callable $test): bool
    {
        return collect($items)->any($test);
    }
}

Keep every macro in one provider. If you also define your own collection macros, register them all in a single CollectionMacrosServiceProvider. Scattering Collection::macro() across providers creates ordering bugs that fail silently and are miserable to trace.

Ship closures, not bare values. A shorthand like $roles->any('admin') hides the comparison operator — and that operator is the semantics of the call. Use it for prototyping only; commit closures with explicit ===.

Gotchas and Tips

Strict vs loose comparison is the only real defect class. If the macro uses == where call sites assume ===, you get silent boolean drift no reviewer or type checker will catch:

collect(['0'])->any(fn ($v) => $v == 0);   // true
collect(['0'])->any(fn ($v) => $v === 0); // false

Pin this down in a unit test on day one. Write === at every call site.

BadMethodCallException in non-HTTP contexts is the classic production-only failure: the macro resolves fine in controllers (provider booted via discovery) but a queue worker, an early-booting Artisan command, or a misordered package provider throws Method Illuminate\Support\Collection::any does not exist. Check bootstrap/providers.php / config/app.php, then rerun php artisan config:cache — a cache built before the provider was added will bite you.

Octane and long-running workers. Macro registration is boot-time global state. If registration is ever env-gated or feature-flagged, workers that booted before the flip will not have the macro. Register unconditionally, or make worker restart part of the deploy.

any() on an empty collection is false. Correct for guard clauses, wrong for "no invalid items" checks — that is $collection->every(fn ($i) => $i->isValid()), and the two are not negations when the collection is empty. Be explicit about which question you are asking.

Don't shadow the native method. On Laravel 9+, installing the package gives you two any() implementations whose winner depends on registration order. Remove the package when you upgrade; native Collection::any() is a drop-in.

Debugging an unexpected false. The macro short-circuits, so iterate with something that doesn't and dump both sides:

$items->each(fn ($i) => dump([$i, $i->isExpired()]));

Short-circuiting is a guarantee, not a performance argument. any() is O(1) best case and O(n) worst case, identical to contains(). Choose it for readability and dependency policy, never for speed.

The query-count trap. any() is in-memory only. $tenant->subscriptions()->get()->any(...) runs SELECT * and then iterates in PHP. If the underlying question is existence, push it into SQL:

$tenant->subscriptions()->where('expires_at', '<', now())->exists();

Extension points are effectively zero. No config, no events, no driver, no stubs. Need key/value predicates, stricter comparison, or async tests? You fork or vendor it — at which point you are maintaining your own copy anyway, which is the strongest argument for starting from a vendored macro in the first place.

Dependency hygiene. If you ship it, record the decision, run composer audit in CI, and file the removal ticket the day you install. The capability is already absorbed upstream (Laravel 9 native, PHP 8.4 array_any()), so this dependency is guaranteed dead weight at your next platform upgrade.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package