Laravel Custom Collection - DevPark
Development / Laravel

Many times we use to write the code without using the latest possible features which our language or framework provides. In this article I would like to present how we can use a power of Laravel Custom Collection for type hinting problem.

First of all, few word about variables type hinting in functions and errors messages which they produce.

You can write a function with parameters:

If you use in code like this:

You will probably see the error like this:

But if you add type hint:

Then the info will be more concrete:

(for details check the php documentation – link)

Another nice feature which starts with php7 is that we can specify what will return us the method (link).

So another simple example:

But if you will write:

Then error will be


This could be really helpful when you creating interfaces or when you only planning your methods without logic implementation…

Then someone who will write a class which implements this interface, cannot make a mistake, because both parameter and returned value are specified.

OK, this is enough for the intro, now I wanna to present my problem and solution of course

I was writing code which gets waybill for order:

And it was OK, I was pretty sure that I need to pass Order object and I will receive Waybill and can do something with it.

But I was wondering how can I type hint when I need to pass a collection of orders, and also get an collection of Waybills…

Of course I can do something like:

But if somewhere in the code I will do something like that:

…Hmm this also will work because $payments is also a collection type. But the problem will be probably somewhere inside of the method, when I will want to use methods from Order which are not covered in $payments object.

The same happens with the returned type.

So how to pass a collection without losing the destination object interface?

Fortunately Laravel has a solution for that – we can create a CustomCollection for our models.

All I need to do is add newColletion method to my Model class (actually override it):

Now, Eloquent will always return a OrdersCollection instead of standard Collection.

And also create this Class, which even could be empty:

analogously for Waybill.

And finally I can made some changes in my method:

And then be sure what we need to pass, and what we get in return!

PS. Of course, you can create some methods in CustomCollection class and then use them as you wish.

author: Przemek Tkaczyk from DevPark Laravel team