Skip to content

[12.x] Make Fluent class iterable #56218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/Illuminate/Support/Fluent.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
namespace Illuminate\Support;

use ArrayAccess;
use ArrayIterator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\InteractsWithData;
use Illuminate\Support\Traits\Macroable;
use IteratorAggregate;
use JsonSerializable;
use Traversable;

/**
* @template TKey of array-key
Expand All @@ -17,7 +20,7 @@
* @implements \Illuminate\Contracts\Support\Arrayable<TKey, TValue>
* @implements \ArrayAccess<TKey, TValue>
*/
class Fluent implements Arrayable, ArrayAccess, Jsonable, JsonSerializable
class Fluent implements Arrayable, ArrayAccess, IteratorAggregate, Jsonable, JsonSerializable
{
use Conditionable, InteractsWithData, Macroable {
__call as macroCall;
Expand Down Expand Up @@ -245,6 +248,16 @@ public function offsetUnset($offset): void
unset($this->attributes[$offset]);
}

/**
* Get an iterator for the attributes.
*
* @return ArrayIterator<TKey, TValue>
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->attributes);
}

/**
* Handle dynamic calls to the fluent instance to set attributes.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/Support/SupportFluentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,25 @@ public function testMacroable()
'baz' => 'zal',
], $fluent->foo()->all());
}

public function testFluentIsIterable()
{
$fluent = new Fluent([
'name' => 'Taylor',
'role' => 'admin',
]);

$result = [];

foreach ($fluent as $key => $value) {
$result[$key] = $value;
}

$this->assertSame([
'name' => 'Taylor',
'role' => 'admin',
], $result);
}
}

class FluentArrayIteratorStub implements IteratorAggregate
Expand Down
Loading