Laravel Collections – make Method

Laravel Collections - make Method

Laravel Collections ( 8 Lessons )

Laravel Collections is one of the most powerful features of Laravel. Basically, collections are PHP arrays but it’s an Object Oriented approach to deal with PHP arrays.

see full series
  1. Laravel Collections – Introduction to Collections
  2. Laravel Collections – make Method
  3. Laravel Collections – wrap() and unwrap() Methods
  4. Laravel Collections – map() Method
  5. Laravel Collections – times() Method
  6. Laravel Collections – collapse() Method
  7. Laravel Collections – contains() & containsStrict() Methods
  8. Laravel Collections – each() 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.

/**
* 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.

$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.

$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.

$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.

2 comments on “Laravel Collections – make Method

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.