Laravel

Laravel Collections - make Method

Laravel Collections Illuminate\Support\Collection class provides number of static helper functions that help us to create new instance of collection.

28 March 20192 min read239 words
Laravel Collections - make Method

Laravel Collections Illuminate\Support\Collection class provides number of static helper functions that help us to create new instance of collection.

Static API's make method creates a new instance of a collection with the provided array.

Signature

Below is the signature of make method defined in Illuminate\Support\Collection class.

php
/**
* Create a new collection instance if the value isn't one already.
*
* @param  mixed  $items
* @return static
*/
public static function make($items = [])
{
   return new static($items);
}

Usage

Let's create a new collection from an array and check if it is an instance of the collection class.

Assume we have a very simple array like below.

php
$languages = [
    'en'    =>  'English',
    'fr'    =>  'French',
    'de'    =>  'German',
    'sp'    =>  'Spanish'
];

We can convert the above array to a collection using make() method of collection class like below.

php
$languages = [
    'en'    =>  'English',
    'fr'    =>  'French',
    'de'    =>  'German',
    'sp'    =>  'Spanish'
];
use Illuminate\Support\Collection;

$collection = Collection::make($languages);

With above code example, our $languages array is converted to a collection and stored in $collection variable.

We can check if the $collection is an instance of collection class like below.

php
$languages = [
    'en'    =>  'English',
    'fr'    =>  'French',
    'de'    =>  'German',
    'sp'    =>  'Spanish'
];
use Illuminate\Support\Collection;

$collection = Collection::make($languages);

$isCollection = $collection instanceof Collection; // true

If $collection is a collection then it will return true.