Answer the question
In order to leave comments, you need to log in
Laravel how to add a key value to a collection?
Collection {#367 ▼
#items: array:2 [▼
0 => CourtDecision {#369 ▶}
1 => CourtDecision {#371 ▶}
]
}
Collection {#367 ▼
#items: array:2 [▼
0 => CourtDecision {#369 ▶}
1 => CourtDecision {#371 ▶}
],
#total:2
}
Answer the question
In order to leave comments, you need to log in
Well, actually this will work:
BUT I'm 99% sure that you don't really need it. Adding properties dynamically is bullshit and smells bad.
You, in fact, why? Do you need an instance of the collection? Maybe an array is enough?
/**
* @var Illuminate\Support\Collection $collection
*/
$arrayCollection = $collection->toArray();
$arrayCollection['total'] = $collection->count();
use Illuminate\Support\Collection;
class MyCollection extends Collection
{
/**
* @var int
*/
protected $total = 0;
public function __construct($items = [])
{
$this->total = count($items);
parent::__construct($items);
}
public function __get($key)
{
if ('total' === $key) {
return $this->count();
}
parent::__get($key);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question