Skip to content

Collections

David Ciulla edited this page Nov 7, 2026 · 2 revisions

Collections

The Laravex.Support.Collection module provides a fluent, object-oriented interface for working with lists of data. It is a Laravex port of the Laravel Collection concept, implemented as an Elixir struct wrapping a plain list.


Creating Collections

Use Collection.new/1 to create a collection from any enumerable, or the collect/1 Helpers:

alias Laravex.Support.Collection

# From a list
collection = Collection.new([1, 2, 3])

# From a map (values become the list items)
collection = Collection.new(%{a: 1, b: 2})

# Via the collect() helper
import Laravex.Support.Helpers
collection = collect([%{name: "Alice"}, %{name: "Bob"}])

Available Methods

Retrieving Items

Collection.all(collection)
# => [%{name: "Alice"}, %{name: "Bob"}]

Collection.count(collection)
# => 2

Collection.first(collection)
# => %{name: "Alice"}

Collection.last(collection)
# => %{name: "Bob"}

Collection.to_list(collection)
# => [%{name: "Alice"}, %{name: "Bob"}]

# sole — return the only item, or raise if empty / ambiguous
Collection.new([42]) |> Collection.sole()
# => 42

Checking State

Collection.is_empty?(collection)
# => false

Collection.is_not_empty?(collection)
# => true

Transforming

All transformation methods return a new Collection — the original is never mutated.

# map — transform each item
Collection.map(collection, fn user -> Map.put(user, :upper, String.upcase(user.name)) end)

# filter — keep items that match
Collection.filter(collection, fn user -> String.starts_with?(user.name, "A") end)

# reject — remove items that match
Collection.reject(collection, fn user -> is_nil(user.email) end)

# flat_map — map then flatten (nested Collections or lists are flattened one level)
Collection.flat_map(collection, fn user -> Collection.new(user.roles) end)

Iterating

each/2 iterates without transforming and returns the original collection, making it chainable:

Collection.each(collection, fn user -> IO.puts(user.name) end)

Reducing

Collection.reduce(collection, 0, fn user, acc -> acc + user.score end)

Filtering by Field Value

# where/3 — filter by key → value equality (supports atom or string keys)
active_users = Collection.where(collection, :active, true)
active_users = Collection.where(collection, "active", true)

# where/2 — filter with a custom function
Collection.where(collection, fn user -> user.age > 18 end)

# first_where/3 — return first matching item (or nil)
Collection.first_where(collection, :role, "admin")

# first_where/2 — return first item matching a predicate
Collection.first_where(collection, fn u -> u.score > 100 end)

Plucking and Projecting

# pluck — extract a single field into a new Collection
names = Collection.pluck(collection, :name)
# => %Collection{items: ["Alice", "Bob"]}

# only — keep only the given keys on each map item
Collection.only(collection, ["id", "name"])

# except — remove the given keys from each map item
Collection.except(collection, ["password", "remember_token"])

Grouping and Keying

# group_by — group items into a map of Collections keyed by field value
by_role = Collection.group_by(collection, :role)
# => %{"admin" => %Collection{...}, "user" => %Collection{...}}

# group_by with a function
by_initial = Collection.group_by(collection, fn u -> String.first(u.name) end)

# key_by — index items into a plain map keyed by field value
indexed = Collection.key_by(collection, :id)
# => %{1 => %{id: 1, name: "Alice"}, 2 => %{id: 2, name: "Bob"}}

Sorting

# sort_by field (ascending)
sorted = Collection.sort_by(collection, :name)
sorted = Collection.sort_by(collection, "created_at")

# sort_by with a function
sorted = Collection.sort_by(collection, fn u -> u.score end)

Summing

# sum — sum numeric items directly
total = Collection.new([10, 20, 30]) |> Collection.sum()
# => 60

# sum by field
total_score = Collection.sum(collection, :score)

Converting

# to_list — returns the underlying Elixir list
Collection.to_list(collection)

# to_map — converts to a map
# If items are {key, value} tuples: returns a string-keyed map
# Otherwise: returns an index-keyed map (0, 1, 2, …)
Collection.to_map(collection)

# values — strips keys from keyword/map items into a plain list
Collection.values(collection)

Chaining

Because every transformation returns a new Collection, operations chain naturally:

result =
  collection
  |> Collection.filter(fn u -> u.active end)
  |> Collection.sort_by(:name)
  |> Collection.pluck(:email)
  |> Collection.to_list()


Set Operations

# diff — items in the left collection not in the right
Collection.diff(a, b)

# intersect — items present in both collections
Collection.intersect(a, b)
Collection.intersect(collection, [1, 2, 3])

Sliding Windows

Produce overlapping sub-collections of a fixed size (Laravel sliding):

Collection.new([1, 2, 3, 4, 5]) |> Collection.sliding(3)
# => Collection of [Collection{[1,2,3]}, Collection{[2,3,4]}, Collection{[3,4,5]}]

# Optional step (default 1)
Collection.sliding(collection, 3, 2)

Cross Join (Cartesian Product)

Collection.new(["S", "M", "L"]) |> Collection.cross_join(["red", "blue"])
# => Collection of [["S","red"], ["S","blue"], ["M","red"], ["M","blue"], ...]

Wrapping

# Wrap a value: nil → empty, Collection → itself, other → [other]
Collection.wrap(nil)        # => %Collection{items: []}
Collection.wrap(42)         # => %Collection{items: [42]}
Collection.wrap([1, 2])     # => %Collection{items: [1, 2]}
Collection.wrap(collection) # => collection (unchanged)

See Also

  • Helpers — the collect/1 helper
  • Strings — Laravex.Support.Str for string utilities

Clone this wiki locally