Eloquent ORM and Models

Eloquent ORM and Models in PHP: --- Two offices work side by side but speak different languages.


The Analogy: The Bilingual Liaison Between Two Offices

Two offices work side by side but speak different languages. The first is the application office, which thinks in objects: a "user" is a thing with a name and an email and methods it can perform. The second is the database office, which thinks only in tables, rows, and columns -- flat records with no behaviour. Between them sits a bilingual liaison who translates fluently in both directions: when the application says "save this user", the liaison rewrites it as an INSERT the database understands; when the database returns a row, the liaison hands the application a fully-formed user object. An Object-Relational Mapper, or ORM, is that liaison. Eloquent is Laravel's ORM.

The liaison's great gift is that neither office has to learn the other's language. The application programmer writes $user->save() and never composes SQL by hand; the database keeps its rows and columns and never has to understand objects. The translation is centralised in one competent intermediary, so the two offices stay decoupled and each can be reasoned about in its own terms. This is why an ORM feels productive: you manipulate objects, and persistence happens as a side effect of clear, high-level calls.

The liaison also knows the relationships between the offices' records. Told that "a user has many posts", the liaison can, when asked, fetch all the posts belonging to a user without the programmer writing the join. Relationships -- has-many, belongs-to, many-to-many -- are declared once and then traversed as if they were plain properties, the liaison quietly issuing the right queries behind each access.

The failure mode is trusting the liaison so completely that you stop noticing what they actually do. A liaison who is asked, inside a loop, to "fetch the posts for this user" once per user will dutifully make a separate trip to the database office every single time -- the N+1 problem wearing a friendly object-shaped mask. And a liaison who accepts any instruction without question will happily write whatever the application dictates, including a client's attempt to set a field it should never control. The ORM's convenience can hide both a performance cliff and a security hole, precisely because the SQL is no longer in front of you. The liaison is invaluable, but you must still know what conversations they are having on your behalf.


Syntax or Core Structure

These are plain-PHP illustrations of Eloquent's ideas, runnable without the framework. The central pattern is Active Record: a model object represents one row and knows how to persist itself. save inserts when the record is new and updates when it already has an id.

<?php
declare(strict_types=1);

final class Model {
    public function __construct(
        private PDO $pdo,
        public ?int $id = null,
        public string $title = '',
        public bool $done = false,
    ) {}

    public function save(): void {
        if ($this->id === null) {
            $s = $this->pdo->prepare('INSERT INTO tasks (title, done) VALUES (?, ?)');
            $s->execute([$this->title, (int) $this->done]);
            $this->id = (int) $this->pdo->lastInsertId();
        } else {
            $s = $this->pdo->prepare('UPDATE tasks SET title = ?, done = ? WHERE id = ?');
            $s->execute([$this->title, (int) $this->done, $this->id]);
        }
    }

    public static function find(PDO $pdo, int $id): ?self {
        $s = $pdo->prepare('SELECT id, title, done FROM tasks WHERE id = ?');
        $s->execute([$id]);
        $row = $s->fetch(PDO::FETCH_ASSOC);
        if ($row === false) return null;
        return new self($pdo, (int) $row['id'], $row['title'], (bool) $row['done']);
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)');

$t = new Model($pdo, title: 'Write lesson');
$t->save();
echo "created id: {$t->id}\n";

$t->done = true;
$t->save();

$again = Model::find($pdo, $t->id);
echo "reloaded: {$again->title} / ", ($again->done ? 'done' : 'open'), "\n";
echo 'missing: ', var_export(Model::find($pdo, 99), true), "\n";

Output:

created id: 1
reloaded: Write lesson / done
missing: NULL

The first save sees id is null, runs an INSERT, and records the assigned id 1. Setting done to true and calling save again now takes the UPDATE branch because the id is set. Reloading with find reads the row back, casting the stored 1 to the boolean true, so the reloaded task prints done. A lookup for a non-existent id returns null, printed as NULL. This insert-or-update-on-save behaviour is the heart of Active Record, and exactly what Eloquent's $model->save() does.


Technical Depth: Query Builders, Relationships, and the Trade-offs

The fluent query builder

Beyond single-row Active Record, an ORM offers a query builder: chained methods that accumulate clauses and compile to SQL. The chaining reads like the query you mean, and every value is bound rather than concatenated.

MethodAddsExample
whereA filter and a bindingwhere('done', '=', 1)
orderByA sort clauseorderBy('id', 'DESC')
getRuns and returns rows--
<?php
declare(strict_types=1);

final class Query {
    private array $wheres = [];
    private array $bindings = [];
    private string $order = '';
    public function __construct(private PDO $pdo, private string $table) {}
    public function where(string $col, string $op, mixed $val): self {
        $this->wheres[] = "$col $op ?";
        $this->bindings[] = $val;
        return $this;
    }
    public function orderBy(string $col, string $dir = 'ASC'): self {
        $this->order = " ORDER BY $col $dir";
        return $this;
    }
    public function toSql(): string {
        $sql = "SELECT * FROM {$this->table}";
        if ($this->wheres) $sql .= ' WHERE ' . implode(' AND ', $this->wheres);
        return $sql . $this->order;
    }
    public function get(): array {
        $s = $this->pdo->prepare($this->toSql());
        $s->execute($this->bindings);
        return $s->fetchAll(PDO::FETCH_ASSOC);
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)');
$pdo->exec("INSERT INTO tasks VALUES (1,'A',0),(2,'B',1),(3,'C',0),(4,'D',1)");

$q = (new Query($pdo, 'tasks'))->where('done', '=', 1)->orderBy('id', 'DESC');
echo 'sql: ', $q->toSql(), "\n";
foreach ($q->get() as $row) {
    echo $row['id'], ':', $row['title'], "\n";
}

Output:

sql: SELECT * FROM tasks WHERE done = ? ORDER BY id DESC
4:D
2:B

Each chained call returns $this, so the calls compose into one expression. toSql assembles the accumulated clauses -- note the value is a ? placeholder, not the literal, so the query stays safe -- and get binds the collected values on execute. Filtering for done tasks and ordering by id descending returns D then B. Eloquent's builder is this idea with dozens more methods and full relationship support.

Relationships

Declaring "a user has many posts" lets you fetch related rows through a method. Here posts returns the rows whose user_id matches the model's id.

<?php
declare(strict_types=1);

final class UserModel {
    public function __construct(
        private PDO $pdo,
        public int $id,
        public string $name,
    ) {}
    public function posts(): array {
        $s = $this->pdo->prepare('SELECT id, title FROM posts WHERE user_id = ? ORDER BY id');
        $s->execute([$this->id]);
        return $s->fetchAll(PDO::FETCH_ASSOC);
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE posts (id INTEGER PRIMARY KEY, user_id INTEGER, title TEXT)');
$pdo->exec("INSERT INTO posts VALUES (1,1,'Hello'),(2,1,'Second'),(3,2,'Other')");

$ada = new UserModel($pdo, 1, 'Ada');
echo $ada->name, " has:\n";
foreach ($ada->posts() as $p) {
    echo '  - ', $p['title'], "\n";
}
$ben = new UserModel($pdo, 2, 'Ben');
echo $ben->name, ' post count: ', count($ben->posts()), "\n";

Output:

Ada has:
  - Hello
  - Second
Ben post count: 1

Ada's posts returns her two posts; Ben's returns his one. Eloquent declares this as hasMany(Post::class) and lets you traverse it as $user->posts. The convenience is real, but note that calling posts() inside a loop over many users is the N+1 trap in ORM clothing -- the fix is eager loading, Eloquent's with('posts'), which batches the related fetch into one query.


Real World Example: Mass Assignment and the Fillable Guard

One of the ORM's most convenient features -- and most dangerous -- is mass assignment: filling many attributes at once from a request array. Convenient, because a controller can do $user->fill($request) in one line. Dangerous, because a malicious client can add fields you never intended, like is_admin. The guard is a fillable allow-list: only named attributes may be mass-assigned.

<?php
declare(strict_types=1);

final class Account {
    private array $attributes = [];
    private const FILLABLE = ['name', 'email'];

    public function fill(array $input): void {
        foreach ($input as $key => $value) {
            if (in_array($key, self::FILLABLE, true)) {
                $this->attributes[$key] = $value;
            }
        }
    }
    public function get(string $key): mixed {
        return $this->attributes[$key] ?? null;
    }
}

$request = [
    'name'     => 'Mallory',
    'email'    => 'm@x.com',
    'is_admin' => true,
];

$acct = new Account();
$acct->fill($request);

echo 'name: ', $acct->get('name'), "\n";
echo 'email: ', $acct->get('email'), "\n";
echo 'is_admin: ', var_export($acct->get('is_admin'), true), "\n";

Output:

name: Mallory
email: m@x.com
is_admin: NULL

The request smuggles is_admin => true alongside the legitimate name and email. Because fill copies only keys in the FILLABLE allow-list, name and email are set but is_admin is silently ignored, so get('is_admin') returns null. This is exactly Eloquent's $fillable property (or its inverse, $guarded): it turns a convenience into a safe convenience by refusing to mass-assign anything not explicitly permitted. The famous real-world breaches from mass assignment -- users granting themselves admin by adding a form field -- happen precisely when this guard is missing.

The design flaw is that the guard silently ignores disallowed keys rather than rejecting the request, which trades one risk for another. A client that sends is_admin gets a 200 response and a created account, with no signal that part of their input was dropped -- and, more importantly, no signal to the developer that someone is probing for a privilege-escalation hole. Silent filtering is safe against the escalation itself, but it hides the attempt, so the attack leaves no trace in ordinary logs and the team never learns it is being targeted. It also masks honest bugs: a developer who forgets to add a legitimately new field to FILLABLE sees it vanish with no error, and debugging "why is this column always null" can burn hours. A stricter design logs or rejects unexpected keys in sensitive contexts, so a mass-assignment attempt is both blocked and visible. Choosing between silent-and-safe and loud-and-auditable is a real decision, and defaulting to silent because it is easier leaves you blind to exactly the attacks the guard exists to stop.


Common Mistakes

  1. The N+1 trap in disguise. Accessing a relationship inside a loop issues one query per iteration. Eager-load the relationship (Eloquent's with) to batch it into one query.
  1. No mass-assignment guard. Calling fill on raw request data without a fillable allow-list lets clients set fields like is_admin. Always declare $fillable or $guarded.
  1. Treating the ORM as magic. Not knowing what SQL a call generates leads to slow or wrong queries. Inspect the generated SQL when performance matters.
  1. Putting queries in the wrong layer. Scattering model queries through controllers and views couples them to storage. Keep data access in models or repositories.
  1. Loading whole tables to filter in PHP. Fetching all rows then filtering in a loop wastes memory and time. Push the filter into the query with where.
  1. Ignoring the difference between get and first. Fetching a collection when you want one row, or vice versa, is a common slip. Match the retrieval method to the need.
  1. Forgetting timestamps and soft deletes. ORMs often manage created_at, updated_at, and soft-delete columns. Bypassing the ORM's writes skips this bookkeeping.
  1. Over-eager loading. Eager-loading relationships you never use fetches data for nothing. Load only the relationships a given path needs.
  1. Mutating models in bulk one at a time. Updating a thousand rows by loading and saving each is slow. Use a bulk update query when per-row logic is not required.

Best Practices

  • Know the SQL your ORM generates, inspecting it whenever a query is on a hot path or behaves unexpectedly.
  • Eager-load relationships you will traverse in a loop, turning an N+1 into a small fixed number of queries.
  • Declare a fillable allow-list so mass assignment can never set an attribute the client should not control.
  • Push filtering, sorting, and limiting into the query rather than fetching everything and processing in PHP.
  • Keep data access in models or repositories, so controllers and views stay free of query logic.
  • Choose the right retrieval -- a single record versus a collection -- and let the ORM manage timestamps and soft deletes rather than writing around it.
  • Use bulk queries for bulk changes when no per-row logic is needed, instead of loading and saving each row.
  • Load only the relationships a given code path actually uses, avoiding both under- and over-fetching.

Practice Exercises

  1. Build an Active Record Note model with save (insert when new, update when it has an id) and a static find, and demonstrate creating, updating, and reloading a note.
  1. Write a fluent query builder with where, orderBy, and get that compiles to bound SQL, and show it returning filtered, sorted rows along with the SQL it generated.
  1. Model a "has many" relationship with a method that fetches related rows by foreign key, then deliberately call it in a loop and describe how you would eager-load to avoid the N+1.
  1. Implement a fill method guarded by a fillable allow-list, prove that a disallowed key like is_admin is ignored, and then extend it to log an attempt to set a disallowed key.