Skip to content

Commit a4623c2

Browse files
authored
Collection@setAppends, Collection@withoutAppends (#57561)
1 parent 762fbe0 commit a4623c2

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/Illuminate/Database/Eloquent/Collection.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -613,6 +613,27 @@ public function append($attributes)
613613
return $this->each->append($attributes);
614614
}
615615

616+
/**
617+
* Sets the appends on every element of the collection, overwriting the existing appends for each.
618+
*
619+
* @param array<array-key, mixed> $appends
620+
* @return $this
621+
*/
622+
public function setAppends(array $appends)
623+
{
624+
return $this->each->setAppends($appends);
625+
}
626+
627+
/**
628+
* Remove appended properties from every element in the collection.
629+
*
630+
* @return $this
631+
*/
632+
public function withoutAppends()
633+
{
634+
return $this->setAppends([]);
635+
}
636+
616637
/**
617638
* Get a dictionary keyed by primary keys.
618639
*

tests/Database/DatabaseEloquentCollectionTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,27 @@ public function testAppendsAddsTestOnEntireCollection()
570570
$this->assertEquals(['test' => 'test'], $c[0]->toArray());
571571
}
572572

573+
public function testSetAppendsSetsAppendedPropertiesOnEntireCollection()
574+
{
575+
$c = new Collection([new EloquentAppendingTestUserModel]);
576+
$c->setAppends(['other_appended_field']);
577+
578+
$this->assertEquals(
579+
[['other_appended_field' => 'bye']],
580+
$c->toArray()
581+
);
582+
}
583+
584+
public function testWithoutAppendsRemovesAppendsOnEntireCollection()
585+
{
586+
$this->seedData();
587+
$c = EloquentAppendingTestUserModel::query()->get();
588+
$this->assertEquals('hello', $c->toArray()[0]['appended_field']);
589+
590+
$c = $c->withoutAppends();
591+
$this->assertArrayNotHasKey('appended_field', $c->toArray()[0]);
592+
}
593+
573594
public function testNonModelRelatedMethods()
574595
{
575596
$a = new Collection([['foo' => 'bar'], ['foo' => 'baz']]);
@@ -845,3 +866,26 @@ public function __toString()
845866
return $this->key;
846867
}
847868
}
869+
870+
class EloquentAppendingTestUserModel extends Model
871+
{
872+
protected $table = 'users';
873+
protected $guarded = [];
874+
public $timestamps = false;
875+
protected $appends = ['appended_field'];
876+
877+
public function getAppendedFieldAttribute()
878+
{
879+
return 'hello';
880+
}
881+
882+
public function getOtherAppendedFieldAttribute()
883+
{
884+
return 'bye';
885+
}
886+
887+
public function articles()
888+
{
889+
return $this->hasMany(EloquentTestArticleModel::class, 'user_id');
890+
}
891+
}

0 commit comments

Comments
 (0)