How to use Laravel Collections in the Yii2 framework
If you’ve worked with Laravel you will probably be familiar with Collections which are a powerful way to work with sets of data.
The good news is that Laravel collections are actually hosted in a dedicated module which you can pull into other PHP projects. This article will show how you can use the Illuminate Collections package in the Yii2 framework.
Start with a fresh install of Yii2 and hook up a database. We can install the Illuminate Collections dependency using Composer:
composer require illuminate/collections
You can already use the collect() helper method to create a collection.
Next create a folder called ‘query’ in the project root. Now create a class called SuperQuery.php which extends Yii2's ActiveQuery class. We just override the all() method to return a Collection object.
Next create a SuperRecord class which extends Yii2’s ActiveRecord. Here we override the find() method to return a SuperQuery object.
Finally when you define your models, extend the new SuperRecord class. For example if you created a Country model:
And that’s it, now if you call the find() and all() methods you will get an Illuminate Collection back!
Country::find()->all();
The Laravel documentation gives you a useful summary of the available Collection methods: