Closure Variable Binding with use Keyword

📖 1 minute read

When passing closures to Laravel collection methods like whenNotEmpty(), each(), or filter(), variables from the outer scope aren’t automatically available inside the closure. You must explicitly bind them using the use keyword.

Wrong:

$service = app(ReportGenerator::class);
$items->whenNotEmpty(function () {
    $service->generate(); // Error: Undefined variable $service
});

Correct:

$service = app(ReportGenerator::class);
$items->whenNotEmpty(function () use ($service) {
    $service->generate(); // Works!
});

Multiple variables:

$project->tasks->whenNotEmpty(function () use ($taskService, $project) {
    $taskService->processForProject($project);
});

This is a fundamental PHP closure behavior that catches many developers coming from JavaScript where closures automatically capture outer scope.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *