Skip to content

Lesson 16 of 45 · Wiring Things Together

Active Record vs Data Mapper

Intermediate•
lesson•
October 26, 2026•
~11 min read

Two shapes of ORM

Every ORM in PHP is one of two patterns, or a hybrid of them. The names go back to Fowler's Patterns of Enterprise Application Architecture:

  • Active Record. A class represents a row in a database table. The class knows how to find itself, save itself, update itself, and delete itself. The data and the persistence operations live on the same object. Eloquent (Laravel) and Yii's ActiveRecord are examples.

  • Data Mapper. A class represents a domain concept and has no idea where it's stored. A separate class (the mapper) translates between the domain object and the database. Doctrine is the canonical PHP example. Cycle ORM is another.

The difference is in who knows about persistence, and the consequences of that difference compound in a long-lived codebase.

What Active Record looks like

Here Member is an Eloquent model, a class that extends Illuminate\Database\Eloquent\Model:

PHP
<?php declare(strict_types=1); namespace App\Membership; use App\Membership\Exceptions\MemberNotFound; final class ActivateMemberService { public function activate(MemberId $memberId): void { $member = Member::query()->find($memberId->value) ?? throw new MemberNotFound($memberId); $member->status = MemberStatus::Active->value; $member->save(); } }

The Member class knows three things at once:

  • What its data looks like (status, email, etc.).

  • How to read itself from the database (find).

  • How to write itself to the database (save).

That's the Active Record contract. Strengths:

  • Easy to learn. The mapping between class and table is direct.

  • Fast to write. No mapper class, no separate domain model, no schema metadata. The column becomes the property by convention.

  • Low ceremony. Most operations are one or two lines.

  • Strong framework integration. Eloquent integrates with Laravel's validation, queues, events, broadcasts, and many other features for free.

Weaknesses:

  • The class has more than one job. The same class is the row, the persistence API, the relationship navigator, the query builder entry point, and (often) the place business rules end up. Cohesion is fighting an uphill battle here.

  • Tests reach for the database. Calls like find and save need a database, and nothing stops business rules on the model from reaching for them. Logic that sits on the model can be tested without a database, but only if the class stays free of those calls.

  • Coupling to the framework. Eloquent isn't a library you can swap out. The model is tied to Eloquent's conventions and lifecycle.

  • Persistence leaks into business code. Business code ends up dealing with mass-assignment, casts, and scopes.

What Data Mapper looks like

PHP
<?php declare(strict_types=1); namespace App\Membership; use App\Membership\Exceptions\MemberNotFound; use Doctrine\ORM\EntityManagerInterface; final readonly class ActivateMemberService { public function __construct(private EntityManagerInterface $entityManager) {} public function activate(MemberId $memberId): void { $member = $this->entityManager->find(Member::class, $memberId->value) ?? throw new MemberNotFound($memberId); $member->activate(); $this->entityManager->flush(); } }

The Member class is a plain PHP object with properties, methods, and behavior. It doesn't extend a base class or have a save() method. The EntityManager (or repository, or mapper) is the thing that talks to the database. It loads Member objects from rows and writes them back. find() returns a managed entity, so Doctrine tracks changes to it and flush() writes whatever changed, with no second persist() call (that is only for new entities). The mapping lives in attributes on the class, or in separate XML or PHP files.

Strengths:

  • The domain object stays pure. It has no persistence methods and no base class. Mapping attributes, if you use them, are the only Doctrine code in the file.

  • Testable in pure PHP. Constructing a Member, calling activate(), and asserting the result requires no database, no container, no fakes. The behavior of the class is independent of how it's stored.

  • Schema and class can diverge. The class can have a shape that fits the domain. The database can have a shape that fits the storage. The mapper handles the translation. This matters a lot for legacy schemas and for rich domain models.

Weaknesses:

  • Higher ceremony. A separate mapper, a separate config, a separate write step (flush). More moving parts.

  • Steeper learning curve. Doctrine in particular has years of accumulated complexity around metadata, change tracking, and lifecycle events.

  • Less directly integrated with Laravel. Laravel features built for Eloquent don't apply. SerializesModels stores a queued job's Eloquent model as its id and reloads it when the job runs, but a Doctrine entity gets serialized whole, so you pass ids and load entities yourself. The Laravel Doctrine package (laravel-doctrine/orm) fills some of these gaps, such as the unique and exists validation rules, auth and pagination, but queued jobs still take ids.

  • Laravel packages expect Eloquent. Scout's Searchable trait and Cashier's Billable trait go on a class that extends Model, and the roles in spatie/laravel-permission are Eloquent models themselves. A Doctrine entity can't use them.

The honest landscape

In modern PHP, the practical breakdown:

  • Eloquent (Active Record). Ships with Laravel. Fast to write. Hard to keep clean past a certain size, but possible.

  • Doctrine (Data Mapper). The usual ORM in Symfony projects, and what some Laravel teams reach for when the domain gets complex. Higher ceremony. Better long-term shape for rich domain models.

  • Cycle ORM. Another Data Mapper option.

  • Hand-rolled. Repository + raw query builder + plain PHP entities. It's a real option for products that genuinely outgrow what an ORM gives you.

The framework you picked has usually chosen for you: Laravel ships with Eloquent, and Symfony projects typically use Doctrine. The interesting question becomes "given the ORM I'm using, how do I keep the long-term cost manageable?".

The Active Record misuse

The most expensive misuse of Active Record I've seen is letting it be the domain model.

PHP
<?php declare(strict_types=1); namespace App\Membership; use Illuminate\Database\Eloquent\Model; class Member extends Model { // 800 lines of: business rules, persistence calls, // query scopes, relationships, casts, accessors, // mutators, observers, validation, formatting, // factory methods (the testing kind), policies, // notification routing, and a few helper methods // someone added at 2am }

This is the cohesion problem at full stretch. Everything that touches a member ends up here, because the framework gave you one obvious place to put it. The class has many reasons to change. Every test exercises some random subset of all the responsibilities. Refactoring it means untangling every responsibility at once.

The fix is to stop treating the Eloquent model as the domain model.

Eloquent in a "Data Mapper-flavored" way

The Anemic Domain Model vs Rich Domain Model lesson put the rules on the Eloquent Reservation itself, where they hold only while every caller goes through its methods. The next step, which this course's codebase takes from the Repository Pattern lesson on, moves the rules off the Eloquent model:

  • Keep Eloquent. The framework wants it. Don't fight it.

  • Treat the Eloquent model as a persistence object. Its job is to map to and from the database. It can have casts, relationships, and the occasional scope. It shouldn't have business rules.

  • Build a domain model alongside. A Member class (in your business code) that's a plain PHP object with the rich behavior from the Anemic Domain Model vs Rich Domain Model lesson. It doesn't extend anything. It has its own methods. It doesn't know about Eloquent.

  • Use a repository as the mapper. The repository's implementation reads Eloquent rows, maps them to domain objects, and writes domain objects back to rows. That mapping is the thing that gives you Data Mapper benefits inside an Active Record framework.

  • Keep the framework's free wins. Eloquent's relationships, scopes, factories (the testing kind), and migrations are useful. Use them inside the persistence layer. Don't expose them upward.

This is a deliberate hybrid: the framework keeps doing what it's good at, and the domain stays clean.

What the hybrid looks like in code

Here's the Member example from earlier in this lesson, rebuilt as a hybrid. Four pieces: the domain object, the Eloquent row, the repository interface, and the repository implementation that maps between them.

The domain object has no idea a database exists. It uses a MemberId identity object (the same shape as GuestId), a CannotActivateMember exception, a MemberNotFound exception and a MemberStatus backed enum with Pending and Active cases, all omitted here:

PHP
<?php declare(strict_types=1); namespace App\Membership; use App\Membership\Exceptions\CannotActivateMember; final class Member { public function __construct( public readonly MemberId $id, private string $email, private MemberStatus $status, ) {} public function changeEmail(string $email): void { $this->email = $email; } public function activate(): void { if ($this->status !== MemberStatus::Pending) { throw new CannotActivateMember($this->id, $this->status); } $this->status = MemberStatus::Active; } public function email(): string { return $this->email; } public function status(): MemberStatus { return $this->status; } }

The rule lives in activate(): a member can only move from pending to active. No code outside Member can assign a status and skip that check, because the property is private.

Member changes in place on purpose: activate() updates its status and changeEmail() its email, the same way an Eloquent model or a Doctrine entity changes before it's saved. The readonly rules from the Immutable Objects lesson fit the id, which never changes, and the small objects around it, like MemberId.

The Eloquent model is only a row: it has no activate() and no rule, and does nothing beyond mapping to a table. The id is a non-incrementing string because the domain assigns it:

PHP
<?php declare(strict_types=1); namespace App\Membership\Models; use Illuminate\Database\Eloquent\Model; final class MemberModel extends Model { protected $table = 'members'; public $incrementing = false; protected $keyType = 'string'; }

The repository interface is domain-shaped, as in the Repository Pattern lesson. It takes and returns Member, never MemberModel:

PHP
<?php declare(strict_types=1); namespace App\Membership; interface Members { public function withId(MemberId $id): Member; public function save(Member $member): void; }

The implementation is where the mapping happens, in both directions:

PHP
<?php declare(strict_types=1); namespace App\Membership\Infrastructure; use App\Membership\Exceptions\MemberNotFound; use App\Membership\Member; use App\Membership\MemberId; use App\Membership\Members; use App\Membership\MemberStatus; use App\Membership\Models\MemberModel; final readonly class EloquentMembers implements Members { public function withId(MemberId $id): Member { $row = MemberModel::query()->find($id->value); if ($row === null) { throw new MemberNotFound($id); } return new Member( id: new MemberId($row->id), email: $row->email, status: MemberStatus::from($row->status), ); } public function save(Member $member): void { $row = MemberModel::query()->find($member->id->value) ?? new MemberModel(); $row->forceFill([ 'id' => $member->id->value, 'email' => $member->email(), 'status' => $member->status()->value, ]); $row->save(); } }

withId() reads a row and returns a Member. save() updates the existing row, or creates one for a new member. forceFill() skips Eloquent's mass-assignment guard, the same way EloquentReservations does, so MemberModel needs no $fillable list.

This costs the mapping code above, plus the discipline of never letting MemberModel reach business code. Every field is copied across by hand, in both directions, and someone has to keep the two shapes in sync as the schema changes. Packages built on Eloquent add to that cost. Cashier's Billable trait goes on MemberModel, so code that starts a subscription has to reach for the Eloquent model and step around the repository.

It buys the rule in activate(). With a plain Eloquent model, $model->status = 'active'; $model->save(); bypasses the check, because there's nothing stopping direct property assignment. With the hybrid, the only way to move an existing Member from pending to active is Member::activate(), which enforces the pending-to-active rule every time, regardless of which controller, job, or console command calls it.

The same idea applies to an aggregate (a cluster of objects saved together as one unit), with child entities and a repository that saves the aggregate consistently.

In my experience this hybrid is a reasonable default. It's cheaper than switching to Doctrine, avoids the worst of the Active Record costs, and keeps the Data Mapper benefits that matter (rich domain, testability, framework decoupling).

When pure Data Mapper earns its place

There are products where Eloquent (even with the hybrid) is the wrong tool, and Doctrine or hand-rolled persistence is the right call:

  • Genuinely complex domains. Insurance underwriting, financial accounting, regulatory compliance. Domains where the model is too rich to fit in tables-with-Active-Record without distortion.

  • Legacy schemas you don't control. A database designed by someone else, decades ago, that doesn't match anything modern code wants to do. A mapper lets you bridge.

If you're in one of these cases, the cost of Doctrine is justified. If not, Eloquent in the hybrid mode covers most of the same ground.

Pitfalls

Common mistakes in either direction:

Treating the Eloquent model as the source of truth for everything. The model becomes a god object, the pitfall called god models. The fix is the hybrid above.

Building a parallel domain model that no one uses. I've seen teams introduce a "domain layer" alongside Eloquent and then keep using Eloquent everywhere because the domain layer was never the path of least resistance. The result is two layers, double the code, no benefit. If you're going to introduce a domain model, the repository has to be the only way the rest of the application talks to persistence.

Switching to Doctrine without a real reason. "We're refactoring to Data Mapper" without a domain that justifies it is an enormous undertaking with little payoff. The cost of Doctrine includes the entire ecosystem around it (different conventions, different lifecycle, less community help, less Laravel-specific tooling).

Mixing Active Record and Data Mapper randomly. Some classes are Eloquent models, some are mapped manually through a repository, some are just plain. Without a rule, the pattern degrades into chaos. Pick one approach per module and stick with it.

The one thing to remember

If you're using Active Record (Eloquent), the model is the persistence object, and the domain model is something else. Keeping that separation is most of what makes a long-lived Laravel codebase manageable. The repository pattern is the boundary where the two stay apart.

If you're using Data Mapper (Doctrine), that separation is already built into the architecture, at the price of the higher ceremony described above.

Course Content