Skip to content

Eloquex Mutators

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

Eloquex: Mutators & Casting

Eloquex models support type casting, accessor/mutator methods, appended virtual attributes, and mass-assignment protection via fillable / guarded. All of these are defined as optional callbacks in your model module.

Introduction

Attribute transformation in Eloquex happens at two moments:

  1. On assignment (new/1, create/1, save/1) — casts and mutators run before writing to the database.
  2. On read (get_attribute/2, to_map/1) — accessors and reverse casts run when you access a value.

Casts

Declare the casts/0 callback to automatically coerce column values:

defmodule App.Models.Post do
  use Laravex.Eloquex.Model, table: "posts"

  def casts do
    %{
      published:    :boolean,
      settings:     :json,
      tags:         :array,
      published_at: :datetime,
      password:     :hashed
    }
  end
end

Cast Types

Type On write On read
:boolean true/false/"1"/"0"/"on" → true/false true/false
:json Stored as-is (map/list) Decoded if stored as JSON string
:array Stored as-is (list); JSON string decoded on read List
:datetime %DateTime{} → ISO-8601 string String (unchanged)
:hashed Plain string → PBKDF2 hash (see Hashing); already-hashed values left as-is Hash string

The :hashed cast is the idiomatic way to handle password columns — no manual hashing required.

Accessors

Define get_<field>_attribute/1 to transform a value when it is read:

defmodule App.Models.User do
  use Laravex.Eloquex.Model, table: "users"

  defstruct [:id, :first_name, :last_name, :email, :created_at, :updated_at]

  # Accessor: combine first and last name
  def get_full_name_attribute(_value) do
    # `_value` is the raw column value (nil for virtual fields)
    # access the struct via the process dictionary if needed
    "#{Process.get(:laravex_first_name)} #{Process.get(:laravex_last_name)}"
  end
end

A simpler pattern — accessors on actual columns:

def get_email_attribute(value) do
  String.downcase(value || "")
end

Accessors are called by get_attribute/2 and by to_map/1 when serializing.

Mutators

Define set_<field>_attribute/1 to transform a value when it is written:

def set_name_attribute(value) do
  value |> to_string() |> String.trim() |> String.capitalize()
end

Mutators run during create/1 and save/1 via Model.apply_mutators/2.

Appended Attributes

Add computed virtual attributes to to_map/1 output (and therefore JSON serialization) by declaring appends/0:

def appends, do: [:full_name, :is_admin]

def get_full_name_attribute(_), do: "#{user.first_name} #{user.last_name}"
def get_is_admin_attribute(_),  do: role == "admin"

The names in appends/0 are passed through get_attribute/2, which calls the corresponding get_<name>_attribute/1 accessor.

Hidden Attributes

Exclude columns from to_map/1 output (e.g., for JSON responses) by declaring hidden/0:

def hidden, do: [:password, :remember_token]

Mass Assignment: fillable and guarded

Control which attributes can be set via create/1, new/1, or update_or_create/2.

fillable (allow-list)

Only the listed fields are accepted; all others are silently dropped:

def fillable do
  ["name", "email", "bio"]
end

guarded (block-list)

All fields are accepted except those listed. Use ["*"] to block everything:

def guarded do
  ["is_admin", "role"]
end

Default Behaviour

When neither fillable/0 nor guarded/0 is defined, Eloquex is unguarded — all attributes are accepted. System attributes (id, created_at, updated_at, deleted_at, remember_token, email_verified_at) are always fillable regardless of these settings.

Soft Deletes

Enable soft deletes with the soft_deletes: true option:

use Laravex.Eloquex.Model, table: "posts", soft_deletes: true

Add a deleted_at column to the migration:

t = Laravex.Database.Blueprint.timestamp(t, "deleted_at", nullable: true)

The model's query/0 automatically appends WHERE deleted_at IS NULL. Retrieve trashed records with:

App.Models.Post.with_trashed()   # all rows
App.Models.Post.only_trashed()   # only deleted
App.Models.Post.restore(post)    # clears deleted_at
App.Models.Post.force_delete(post)  # permanent delete

Dirty Tracking

App.Models.Post.is_dirty?(post)          # any changes since load?
App.Models.Post.is_dirty?(post, :title)  # specific field changed?
App.Models.Post.is_clean?(post)          # inverse of is_dirty?
App.Models.Post.is_clean?(post, :title)

App.Models.Post.get_changes(post)        # map of changed fields → new values

The original attribute snapshot is stored in the process dictionary when a model is loaded (via Model.sync_original/1) and compared on save/1 to generate a minimal UPDATE statement.

Reading the Original Value

# Full map of original attributes before any changes
original = App.Models.Post.get_original(post)

# Single original attribute
original_title = App.Models.Post.get_original(post, :title)

Checking What Changed After Save

After save/1, Eloquex records which fields changed in the database update:

post = App.Models.Post.save(post)

App.Models.Post.was_changed(post)         # true if any field was updated
App.Models.Post.was_changed(post, :title) # true if :title was in the UPDATE

was_changed reflects the diff from the previous save, while is_dirty? reflects the diff from the current loaded snapshot.

See Also

Clone this wiki locally