Repository navigation
Eloquex Mutators
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.
Attribute transformation in Eloquex happens at two moments:
-
On assignment (
new/1,create/1,save/1) — casts and mutators run before writing to the database. -
On read (
get_attribute/2,to_map/1) — accessors and reverse casts run when you access a value.
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| 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.
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
endA simpler pattern — accessors on actual columns:
def get_email_attribute(value) do
String.downcase(value || "")
endAccessors are called by get_attribute/2 and by to_map/1 when serializing.
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()
endMutators run during create/1 and save/1 via Model.apply_mutators/2.
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.
Exclude columns from to_map/1 output (e.g., for JSON responses) by declaring hidden/0:
def hidden, do: [:password, :remember_token]Control which attributes can be set via create/1, new/1, or update_or_create/2.
Only the listed fields are accepted; all others are silently dropped:
def fillable do
["name", "email", "bio"]
endAll fields are accepted except those listed. Use ["*"] to block everything:
def guarded do
["is_admin", "role"]
endWhen 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.
Enable soft deletes with the soft_deletes: true option:
use Laravex.Eloquex.Model, table: "posts", soft_deletes: trueAdd 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 deleteApp.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 valuesThe 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.
# 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)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 UPDATEwas_changed reflects the diff from the previous save, while is_dirty? reflects the diff from the current loaded snapshot.
- Eloquex — Getting started with models
- Eloquex-Relationships — Relation loading
-
Hashing — PBKDF2 details behind
:hashedcast
Laravex — Laravel-faithful application skeleton & runtime for Elixir.
GitHub
·
Docs
·
Limitations
·
Laravel Docs
Not affiliated with Laravel LLC or the Elixir core team. Built to feel like Laravel on the BEAM.
- Home
- Installation
- Configuration
- Directory-Structure
- Request-Lifecycle
- Service-Container
- Service-Providers
- Deployment
- Routing
- Middleware
- CSRF-Protection
- Controllers
- Requests
- Responses
- Views
- Blade-Templates
- Asset-Bundling
- Session
- Validation
- Error-Handling
- Logging
- Artisan-Console
- Broadcasting
- Cache
- Collections
- Events
- File-Storage
- Helpers
- HTTP-Client
- Localization
- Notifications
- Pipeline
- Queues
- Rate-Limiting
- Strings
- Task-Scheduling