Skip to content

Using firstWhere() inside when() does not yield the expected result #44712

@troccoli

Description

@troccoli
  • Laravel Version: 9.35.1
  • PHP Version: 8.1.11
  • Database Driver & Version:

Description:

When using firstWhere() inside a when() on a collection I don't get what I think I should.

Steps To Reproduce:

On a brand new Laravel project, add the following Unit test

<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

class FirstWhereTest extends TestCase
{
    public function test_firstWhere(): void
    {
        $collection = collect([
            ['name' => 'John'],
            ['name' => 'Paul'],
        ]);

        $notFound = $collection->firstWhere('name', '=', 'Peter');

        $this->assertNull($notFound);

        $notFoundUsingWhen = $collection->when(
            true,
            fn ($collection) => $collection->firstWhere('name', '=', 'Peter')
        );

        $this->assertNull($notFoundUsingWhen);
    }
}

The second assertion fails, as $notFoundUsingWhen is actually the whole collection, rather that null

Note
The unit test passes in Laravel 8.83.25

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