Laravel Collections – make Method
Laravel Collections ( 11 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- Laravel Collections – Introduction to Collections
- Laravel Collections – make Method
- Laravel Collections – wrap() and unwrap() Methods
- Laravel Collections – map() Method
- Laravel Collections – times() Method
- Laravel Collections – collapse() Method
- Laravel Collections – contains() & containsStrict() Methods
- Laravel Collections – each() Method
- Laravel Collection – Using toJson() Method
- Laravel Collection – Filtering Collection Items using where()
- Laravel Collection – Using splice() Method to Remove Items
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; // trueIf $collection is a collection then it will return true.
