One thing when working with Laravel that I have used the most, are the Laravel Collections. They come handy when you need to manipulate and filter arrays. Collections basically are a wrapper for working with arrays of data. Collections provide a lot of powerful and useful methods to manipulate the arrays. You can check them out here. Laravel comes by default, with Collections, but what if you wanted to use them in your PHP project? How can you install and use Collections in your non-Laravel project? In this article, we will provide a step by step instructions on how to setup and use Collections in your project.

Table of Contents

Prerequisites

To follow this guide, you will need the following components:

  • PHP 8 or higher
  • Composer
  • illuminate/collections package

Use Collections outside Laravel

If you want to use Collections in your non-Laravel PHP projects, it's a prerequisite that you have installed Composer in your project. If you want a guide on how to install Composer, please check this article. The instructions are explained step by step.

After you have installed Composer in your project, next you need to install the illuminate/collections package in your project as well. To do that, you need to run the next command in the terminal.

composer require illuminate/collections

This will install a latest stable version of the illuminate/collections package in your project. In our project we are using the latest stable version 9.52. So now you are ready to use Collections in your project.

In our case, in the root of our directory, we have created index.php file where we will use Collections in it. But before using them, we need to include the autoload file, so all of the dependencies that we have previously installed, are loaded and ready to use.

include './vendor/autoload.php';

Now you are ready to write your code and use Collections. In the next part, it's explained how to use Collections in your project.

How to use Collections?

Collections act as wrapper for working with arrays of data. Using them is very convenient and easy. There are two ways to create Collections. You can create them using the collect() helper function or by instantiating the Collection class. Both approaches return an

Illuminate\Support\Collection object.

use Illuminate\Support\Collection;

$fruits = collect(["apples", "oranges", "strawberries"]);
$fruits->all();   //["apples", "oranges", "strawberries"]

$fruits = new Collection(["apples", "oranges", "strawberries"]);
$fruits->all();   //["apples", "oranges", "strawberries"]

The all() method which is used in the code block above, is a method that provides the items in the Collection. You could also use the method toArray() to retrieve the items.

Conclusion

In this article, we installed Collections in our non-Laravel PHP project and used them. If you want to learn more about Laravel Collections check the official documentation.

The code from this article is available at my Github.