Skip to content

[9.x] Conditionable::when returns Collection when callback or default return empty value (e.g. 0) #40877

Closed
@spaceemotion

Description

@spaceemotion
  • 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":

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)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions