-
Notifications
You must be signed in to change notification settings - Fork 11.7k
Closed
Labels
Description
- Laravel Version: 9.0
- PHP Version: 8.1.2
- Database Driver & Version: MySQL 8
Description:
I have the following snippet that calculates a number of serviced hours based on a condition:
$hours = $patient->serviceEntries->whenNotEmpty(
static fn (Collection $entries) => $calculator->calcRegular($entries),
static fn () => 0,
);In case the calculator returns 0 hours (or the entries are empty) the expected result would be 0.
However, the function returns the collection itself, as the Conditionable trait returns $this when the return value is "empty":
framework/src/Illuminate/Conditionable/Traits/Conditionable.php
Lines 28 to 32 in ca33630
| if ($value) { | |
| return $callback($this, $value) ?: $this; | |
| } elseif ($default) { | |
| return $default($this, $value) ?: $this; | |
| } |
The same logic applies to the unless function as well.
A possible solution is to use ?? instead of ?:. Not sure if this is a breaking change though (as it has worked before).
Steps To Reproduce:
$shouldBeZero = collect([1,2,3])->whenNotEmpty(fn () => 0, fn () => 0);
// returns the collection instance (with 1,2,3 as values)