📖 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.
Leave a Reply