Create collection instance for given array in Laravel

Laravel provides many helpers that come in handy in multiple ways and saves developer’s work. One of such is collect() which can be used easily to create Collection instance for the provided array.

The collection is one of the most powerful features provided by Laravel which also used within Eloquent

Tested with Laravel versions 5.8, 6, and 7.

We need to import the Illuminate\Support\Collection namespace with the use keyword.

Kindly check for your version on the official DOC for Laravel collect() Helper. This link will take you to Laravel 8 Documentation.

Syntax

collect($data)

Parameters

$array (necessary)

  • The collect() helper accepts an array parameter whose collection instance is needed.

Return value

  • Laravel collect() helper will return a new Illuminate\Support\Collection instance.

Example

$languages = [
  'Gujarati',
  'Hindi',
  'Sanskrit',
  'Tamil',
  'Urdu',
];

$languageCollection = collect($languages);

Resources

Happy 😄 coding

With ❤️ from 🇮🇳

Avatar

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳

Next
Previous

Related