Skip to content

Eloquex Resources

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

Eloquex: API Resources

Laravex.Http.Resource provides Laravel-style JSON API resources. A resource transforms a single model (or collection of models) into a JSON-serializable map, letting you control exactly which fields are exposed, conditionally include relation data, and add metadata.

Introduction

Create a resource module under app/Http/Resources/ using use Laravex.Http.Resource:

defmodule App.Http.Resources.PostResource do
  use Laravex.Http.Resource

  def to_map(post) do
    merge(%{
      id:         post.id,
      title:      post.title,
      body:       post.body,
      created_at: post.created_at,
      user:       when_loaded(post, :user, &App.Http.Resources.UserResource.to_map/1),
      comments:   when_loaded(post, :comments)
    })
  end
end

to_map/1

The only required callback. Return a map representing the resource. Use merge/1 to automatically strip any when_loaded values that were not eagerly loaded.

when_loaded

Conditionally include a relation only when it has been eager-loaded (via Model.with/2 or Model.load/2). If the relation is not loaded, when_loaded returns a sentinel "missing" value that merge/1 removes from the output map.

# Include the raw relation value
when_loaded(post, :comments)

# Transform the loaded value with a function
when_loaded(post, :user, &App.Http.Resources.UserResource.to_map/1)

# Transform a list relation
when_loaded(post, :comments, fn comments ->
  Enum.map(comments, &App.Http.Resources.CommentResource.to_map/1)
end)

merge/1

Strips any missing-value sentinels from the map so the final JSON never contains placeholder keys:

def to_map(post) do
  merge(%{
    id:    post.id,
    title: post.title,
    tags:  when_loaded(post, :tags)   # omitted if not loaded
  })
end

merge_when

Conditionally merge a sub-map based on a boolean condition:

def to_map(post) do
  merge(%{id: post.id, title: post.title})
  |> Map.merge(merge_when(post.published, %{published_at: post.published_at}))
end

merge_when(condition, attrs) returns merge(attrs) when condition is truthy, or %{} otherwise.

additional

Override additional/1 to append metadata to every response:

def additional(_post) do
  %{meta: %{version: "1.0"}}
end

The returned map is merged into the top-level response after the data key.

wrap

By default every resource is wrapped under a "data" key. Override wrap/0 to change this:

def wrap, do: "post"    # => {"post": {...}}
def wrap, do: false     # => {...}  (no wrapping)

Sending Resource Responses

# Single resource
def show(request) do
  post =
    App.Models.Post.find_or_fail(request.route_params["post"])
    |> App.Models.Post.load(:user)

  App.Http.Resources.PostResource.make(post)
end

make/1 calls to_map/1, wraps the result, merges additional/1, and returns a %Laravex.Http.Response{} with status 200 and Content-Type: application/json.

when_cond

Laravel's $this->when — include a value only when a condition is truthy. Missing values are stripped by merge/1:

def to_map(user) do
  merge(%{
    id: user.id,
    role: when_cond(user.admin?, "admin")
  })
end

Pass a third argument for an explicit else value: when_cond(condition, value, default).

Resource Collections

Laravex.Http.ResourceCollection is the Laravel ResourceCollection / UserResource::collection($users) analogue. It maps each item through a resource's to_map/1, wraps the list, merges collection-level additional/1, and — when given a paginator — attaches links and meta.

Anonymous collections

Every resource module gets collection/1 and collection_response/1 for free:

# Struct only (Laravel UserResource::collection($users))
coll = App.Http.Resources.UserResource.collection(users)
Laravex.Http.ResourceCollection.response(coll)

# One-shot JSON response
App.Http.Resources.UserResource.collection_response(users)

# Chain additional / wrap on the struct
App.Http.Resources.UserResource.collection(users)
|> Laravex.Http.ResourceCollection.additional(%{meta: %{source: "index"}})
|> Laravex.Http.ResourceCollection.wrap("users")
|> Laravex.Http.ResourceCollection.response()

Named collection modules

Define a dedicated collection with use Laravex.Http.ResourceCollection, collects: ...:

defmodule App.Http.Resources.UserCollection do
  use Laravex.Http.ResourceCollection, collects: App.Http.Resources.UserResource

  def additional(_resources) do
    %{meta: %{source: "users"}}
  end
end

# JSON response
App.Http.Resources.UserCollection.make(users)

# Envelope map without an HTTP response
App.Http.Resources.UserCollection.to_map(users)

# Struct for further chaining
App.Http.Resources.UserCollection.new(users)

Generate one with Artisan:

./artisan make:resource UserCollection --collection
# or
./artisan make:resource UserCollection -c

The generator sets collects: to App.Http.Resources.UserResource by stripping a trailing Collection (and appending Resource when needed).

Pagination envelope

Pass a pager map (paginate / simple_paginate) to a collection. Laravex detects data + pagination meta and emits Laravel-shaped links / meta:

def index(request) do
  page  = String.to_integer(Map.get(request.params, "page", "1"))
  pager = App.Models.Post.paginate(15, page, path: "/api/posts")

  # Equivalent helpers:
  App.Http.Resources.PostResource.paginated(pager)
  # App.Http.Resources.PostResource.collection_response(pager)
  # App.Http.Resources.PostCollection.make(pager)
end

Example JSON:

{
  "data": [{ "id": 1, "title": "Hello" }],
  "links": {
    "first": "/api/posts?page=1",
    "last": "/api/posts?page=3",
    "prev": null,
    "next": "/api/posts?page=2"
  },
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 3,
    "path": "/api/posts",
    "per_page": 15,
    "to": 15,
    "total": 40
  }
}

paginated/1 on a resource is an alias for collection_response/1 and goes through ResourceCollection (not a separate paginator path).

Full Example

defmodule App.Http.Resources.UserResource do
  use Laravex.Http.Resource

  def wrap, do: "user"

  def to_map(user) do
    merge(%{
      id:         user.id,
      name:       user.name,
      email:      user.email,
      verified:   not is_nil(user.email_verified_at),
      posts:      when_loaded(user, :posts,
                    fn posts -> Enum.map(posts, &App.Http.Resources.PostResource.to_map/1) end),
      posts_count: when_loaded(user, :posts_count)
    })
    |> Map.merge(merge_when(user.is_admin, %{admin_since: user.created_at}))
  end

  def additional(_user), do: %{meta: %{api_version: "1"}}
end
# In a controller:
users = App.Models.User.all()
users = App.Models.User.with(users, [:posts])

App.Http.Resources.UserResource.collection_response(users)

See Also

Clone this wiki locally