Repository navigation
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.
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.Modelis the lower-level compatibility layer. Preferuse Laravex.Eloquex.Modelfor new code.
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
endThe table: option is required. Struct fields must match column names.
# 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.
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.
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.
App.Models.Post.delete(post) # soft delete if `soft_deletes: true`
App.Models.Post.force_delete(post) # always hard-deletesEnable by passing soft_deletes: true:
use Laravex.Eloquex.Model, table: "posts", soft_deletes: truedelete/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 setAdd the column in a migration with Blueprint.soft_deletes/1 (see Migrations).
# 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"}
)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()import Laravex.Eloquex.Model, only: [global_scope: 2]
global_scope :published do
Laravex.Database.Query.where(query, "published", 1)
endApplied automatically to every query/0 call unless query(without_global_scopes: true) is used.
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.
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 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.
# 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.
# 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 without firing model lifecycle events
post = App.Models.Post.save_quietly(post)-
Eloquex-Relationships —
has_many,belongs_to,attach/detach/sync -
Eloquex-Mutators — Casts, accessors,
fillable, soft deletes - Eloquex-Resources — JSON API resources
- Eloquex-Factories — Test data factories
- Migrations — Schema definition
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