K
K
kaxa32012019-11-11 17:38:49
Laravel
kaxa3201, 2019-11-11 17:38:49

Laravel how to add a key value to a collection?

Collection {#367 ▼
  #items: array:2 [▼
    0 => CourtDecision {#369 ▶}
    1 => CourtDecision {#371 ▶}
  ]
}

I want to add total to this collection
, that's what I want to get
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

1 answer(s)
K
Kirill Alekseev, 2019-11-11
@kspitfire

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();

If you desperately need an object with such a structure, inherit the Laravel Illuminate\Support\Collection class and add a new property there. This will be the most correct way.
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);
    }
}

But then again, magical methods are also a path to hell.
In short, you want the weird.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question