Posted: 07-06-2020

Extend Laravel Collection

Extend Laravel Collection

The Illuminate\Support\Collection class provides a convenient wrapper for working with PHP arrays of data. Laravel Collection class allows us to chain its methods to perform fluent mapping and reducing of the underlying array.

But Laravel also provides a very useful new Collection() method to extend the base Eloquent collection class.

In one of my last project customer ask me to show on google maps markers  the sequence of own agents appointments on the daily basis.

So i tried to extend the Laravel collection class to map the correct agents visits sequence.

First of all I created a new collection class VisitCollection and the I added the method  agentVisitSequence responsible to map the correct sequence (visit time) the agent appointments.

Now we need to tell our Visit class to utilize theVisitCollection instead of the base eloquent collection. We can achieve this by overriding the model’s newCollection() method.

Then when we retrieve visit models from the database, we will be able to use the new domain collection method in this way:

Finally ......

You can find additional resource about how to extend Laravel collection here:

https://timacdonald.me/giving-collections-a-voice/