Skip to content

Eloquex

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

Eloquex

Eloquex is Laravex's Eloquent-shaped ORM. It sits on top of Database (SQLite via the sqlite3 CLI) and provides an expressive, model-centric interface for all database interactions.

Introduction

The core module is Laravex.Eloquex.Model. Every Eloquex model is a plain Elixir struct with schema-aware class methods, automatic casting, dirty tracking, soft deletes, relations, and pagination.

Laravex.Database.Model is the lower-level compatibility layer. Prefer use Laravex.Eloquex.Model for new code.

Defining a Model

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

  # Struct fields — one per database column
  defstruct [
    :id,
    :user_id,
    :title,
    :body,
    :published,
    :created_at,
    :updated_at
  ]

  # Relations (see Eloquex-Relationships)
  def relations do
    [
      belongs_to(:user, App.Models.User),
      has_many(:comments, App.Models.Comment)
    ]
  end

  # Type casts (see Eloquex-Mutators)
  def casts do
    %{published: :boolean}
  end

  # Mass-assignment allow-list
  def fillable do
    ["title", "body", "published", "user_id"]
  end
end

The table: option is required. Struct fields must match column names.

Retrieving Models

# All rows
posts = App.Models.Post.all()

# Single record by primary key
post = App.Models.Post.find(1)        # returns nil if not found
post = App.Models.Post.find_or_fail(1) # raises ModelNotFoundException

# First record
post = App.Models.Post.first()

# Query builder access
posts =
  App.Models.Post.query()
  |> Laravex.Database.Query.where("published", 1)
  |> Laravex.Database.Query.order_by("created_at", "desc")
  |> Laravex.Database.Query.get()
  |> Enum.map(&App.Models.Post.from_row/1)

query/0 returns a %Laravex.Database.Query{} scoped to the model's table, with any registered global scopes applied.

Creating Records

post = App.Models.Post.create(%{
  "title"     => "Hello Laravex",
  "body"      => "An introduction.",
  "user_id"   => 1,
  "published" => true
})
# => %App.Models.Post{id: 1, title: "Hello Laravex", ...}

create/1 runs the attributes through fillable?/2, applies casts and mutators, then issues an INSERT RETURNING id.

Updating Records

post = %{post | title: "Updated Title"}
post = App.Models.Post.save(post)

save/1 detects changed fields via dirty tracking and issues a targeted UPDATE. Unchanged fields are not sent to the database.

Deleting Records

App.Models.Post.delete(post)   # soft delete if `soft_deletes: true`
App.Models.Post.force_delete(post)  # always hard-deletes

Soft Deletes

Enable by passing soft_deletes: true:

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

delete/1 sets deleted_at instead of removing the row. query/0 automatically excludes soft-deleted rows with WHERE deleted_at IS NULL.

App.Models.Post.with_trashed()      # all rows including deleted
App.Models.Post.only_trashed()      # only deleted rows
App.Models.Post.restore(post)       # clears deleted_at
App.Models.Post.force_delete(post)  # permanent hard delete
App.Models.Post.trashed?(post)      # true when deleted_at is set

Add the column in a migration with Blueprint.soft_deletes/1 (see Migrations).

First-or-Create / First-or-New / Update-or-Create

# Find matching record or create it
user = App.Models.User.first_or_create(
  %{"email" => "alice@example.com"},
  %{"name" => "Alice"}
)

# Find matching record or build an unsaved struct (Laravel `firstOrNew`)
user = App.Models.User.first_or_new(
  %{"email" => "alice@example.com"},
  %{"name" => "Alice"}
)
# user.id == nil when no record was found — call save() to persist it

# Find and update, or create
user = App.Models.User.update_or_create(
  %{"email" => "alice@example.com"},
  %{"name" => "Alice Updated"}
)

Scopes

Local Scopes

defmodule App.Models.Post do
  use Laravex.Eloquex.Model, table: "posts"
  import Laravex.Eloquex.Model, only: [scope: 2]

  scope :published do
    Laravex.Database.Query.where(query, "published", 1)
  end

  scope :recent do
    Laravex.Database.Query.order_by(query, "created_at", "desc")
  end
end

# Usage
App.Models.Post.scope(App.Models.Post.query(), :published)
|> Laravex.Database.Query.get()

Global Scopes

import Laravex.Eloquex.Model, only: [global_scope: 2]

global_scope :published do
  Laravex.Database.Query.where(query, "published", 1)
end

Applied automatically to every query/0 call unless query(without_global_scopes: true) is used.

Pagination

pager = App.Models.Post.paginate(15, page, path: "/posts")
pager = App.Models.Post.simple_paginate(15, page, path: "/posts")

See Pagination for the full pager map format and link rendering.

Increments & Touch

App.Models.Post.increment(post, :views)        # +1
App.Models.Post.decrement(post, :views, 5)     # -5
App.Models.Post.touch(post)                    # sets updated_at to now

Upsert & Insert-or-Ignore

# Upsert rows on conflict of unique_by columns
App.Models.Post.upsert(
  [%{"email" => "a@b.c", "name" => "Alice"}],
  ["email"],       # unique_by
  ["name"]         # columns to update on conflict
)

# Insert, silently skip on duplicate key
App.Models.Post.insert_or_ignore([
  %{"email" => "a@b.c"},
  %{"email" => "b@c.d"}
])

Both delegate to Laravex.Database.Query.upsert/4 and Query.insert_or_ignore/2, using SQLite's ON CONFLICT … DO UPDATE and INSERT OR IGNORE syntax.

Fresh & Replicate

# Re-fetch a new instance from the database (returns nil if deleted)
refreshed = App.Models.Post.fresh(post)

# Re-fetch with specific relations loaded
refreshed = App.Models.Post.fresh(post, [:user, :comments])

# Clone the struct without persisting (drops id/timestamps)
copy = App.Models.Post.replicate(post)

# Exclude additional columns from the clone
copy = App.Models.Post.replicate(post, ["slug"])

fresh/2 always queries the database. replicate/2 creates an unsaved in-memory copy — call save/1 to persist it.

Load Count / Load Missing / Without

# Attach relation counts to already-loaded models
posts = App.Models.Post.with_count(posts, [:comments])
# post.comments_count is now available

# Eager-load only relations not yet loaded
posts = App.Models.Post.load_missing(posts, [:user, :comments])

# Unload previously loaded relations from a model
post = App.Models.Post.without(post, [:comments])

Save Quietly

# Save without firing model lifecycle events
post = App.Models.Post.save_quietly(post)

See Also

Clone this wiki locally