Lumberjack
WebsiteRareloopTimber DocumentationTwig Documentation
v6
v6
  • Introduction
  • What's New
  • Upgrade Guide
  • Getting Started
    • Installation
    • Configuration
  • The Basics
    • Lifecycle
    • Routing
    • WordPress Controllers
    • Post Types
    • Query Builder
    • View Models
    • HTTP Requests
    • HTTP Responses
    • Middleware
    • Sessions
    • Helpers
    • Collections
  • Container
    • Using the Container
    • Service Providers
    • Facades
  • Misc
    • Contributing
    • Notable Mentions
    • Code of Conduct
    • View on GitHub
    • View Docs on GitHub
    • Submit an issue
Powered by GitBook
On this page
  1. The Basics

Collections

Collections are a thin wrapper around arrays that make them much easier to work with.

PreviousHelpersNextUsing the Container

Last updated 2 years ago

You can create a collection in a couple of ways:

use Illuminate\Support\Collection;

$data = new Collection(['Jayne', 'Milo']);

// or using the global helper
$data = collect(['Jayne', 'Milo']);

If you are used to working with arrays, you can continue using them in the same way.

$data = collect(['Jayne', 'Milo']);

// Get the first name, or if it doesn't exist set the value to null
$firstName = $data[0] ?? null;

However, collections come with a huge assortment of handy functions that can make your life easier.

$data = collect(['Jayne', 'Milo']);

// Get the first name, or if it doesn't exist set the value to null
$firstName = $data->first();

For a list of the available methods, please refer to their documentation:

Note: Laravel's collections may change over time as they add/remove features etc. Make sure you are always referring to the correct version of their documentation.

Extending collections

Similar to post types and the query builder, you can add your own methods to the collection class using macros. For more information about this, please refer to Laravel's documentation:

https://laravel.com/docs/9.x/collections#available-methods
https://laravel.com/docs/9.x/collections#extending-collections