🚀 Day 5 : Advanced Laravel : Eloquent ORM — What REALLY Happens When Database Rows Become PHP Objects?

Eloquent ORM — What REALLY Happens When Database Rows Become PHP Objects

You write:

$users = User::with('orders')->get();

Laravel returns a collection of User models with their orders.

Simple, right?

But what happens internally?

  • How does Laravel convert database rows into Eloquent models?

  • When are relationships actually queried?

  • Why can accessing a relationship unexpectedly execute SQL?

  • How does Eloquent know whether a model has changed?

  • Why don't mass updates trigger model events?

Understanding these mechanisms is essential for building high-performance Laravel applications.

Let's investigate. 👇


1. Eloquent doesn't directly return database rows

Consider:

$users = User::query()->get();

The database returns rows similar to:

[
    [
        'id' => 1,
        'name' => 'Jay',
        'email' => 'jay@example.com',
    ],
    [
        'id' => 2,
        'name' => 'Alex',
        'email' => 'alex@example.com',
    ],
]

But Eloquent doesn't simply return this array.

It converts the database results into model instances.

This process is called Hydration.

Conceptually:

Database Query ↓ Raw Database Results ↓ Eloquent Builder ↓ Hydrate Model Instances ↓ Eloquent Collection ↓ Application Code

Internally, Eloquent's builder uses methods such as:

get()
hydrate()
newFromBuilder()

The newFromBuilder() method creates a model instance from database attributes.

This is where raw database data becomes an Eloquent model.

Advanced takeaway: Hydration has a cost. Loading thousands of models means creating thousands of PHP objects, not simply retrieving an array of rows.


2. What happens during Model Hydration?

Let's examine the internal concept.

$model = new User();

$model->setRawAttributes($attributes, true);

The second argument tells Eloquent to synchronize the model's original attributes.

This matters because Eloquent tracks:

  • Current attributes

  • Original attributes

  • Dirty attributes

  • Changed attributes

For example:

$user = User::find(1);

$user->name = 'Updated Name';

var_dump($user->isDirty('name'));

Result:

true

Why?

Because Eloquent compares the current attribute value against its original value.

You can inspect:

$user->getOriginal();
$user->getDirty();
$user->getChanges();
$user->isClean();
$user->wasChanged();

This internal tracking powers Eloquent's update behavior.


3. Relationship Loading: Lazy vs Eager Loading

This is where many production performance problems begin.

Consider:

$users = User::all();

foreach ($users as $user) {
    echo $user->orders->count();
}

If 100 users are retrieved, accessing orders can trigger an additional query for every user.

Conceptually:

1 Query: Fetch Users

100 Queries: Fetch Orders for Each User

Total: 101 Queries

This is the famous N+1 query problem.

Now consider:

$users = User::with('orders')->get();

Eloquent retrieves users and then performs eager relationship loading.

Conceptually:

Query 1: Fetch Users ↓ Query 2: Fetch Orders ↓ Match Orders to Users ↓ Return Models with Loaded Relationships

For this simple relationship, the number of queries is typically reduced from 101 to 2.

Important: Eager loading does not necessarily mean one SQL JOIN. Eloquent commonly executes separate queries and matches the results in memory.


4. How Does Eloquent Remember Loaded Relationships?

Consider:

$user = User::with('orders')->first();

$user->orders;
$user->orders;
$user->orders;

Does Laravel execute the same relationship query three times?

Normally, no.

Eloquent stores loaded relationship results in its internal $relations array.

Conceptually:

User Model
    |
    |-- attributes
    |
    |-- original attributes
    |
    |-- relations
          |
          |-- orders
          |-- profile

This explains why accessing an already-loaded relationship generally doesn't execute another query.

You can inspect relationship loading:

$user->relationLoaded('orders');

You can also explicitly load relationships:

$user->load('orders');

Or load only relationships that aren't already loaded:

$user->loadMissing('orders');

This distinction becomes particularly useful when multiple application layers work with the same model.


5. Lazy Loading Prevention: Catch N+1 Before Production

Laravel provides a useful mechanism to detect accidental lazy loading.

Inside a service provider:

use Illuminate\Database\Eloquent\Model;

public function boot(): void
{
    Model::preventLazyLoading(
        ! app()->isProduction()
    );
}

Now accidental relationship access can raise a lazy-loading violation instead of silently executing unexpected queries.

You can also configure a custom lazy-loading violation handler.

Why is this useful?

Because N+1 problems are often introduced accidentally during feature development.

A developer adds:

$user->profile->avatar;

inside a loop, and suddenly the endpoint becomes significantly slower.

Catching this during development is much cheaper than diagnosing it after deployment.


6. Model Events: What Happens During Save?

Consider:

$user = new User();

$user->name = 'Jay';

$user->save();

Eloquent has a lifecycle of model events.

A simplified creation lifecycle:

saving ↓ creating ↓ INSERT Query ↓ created ↓ saved

For an existing model being updated:

saving ↓ updating ↓ UPDATE Query ↓ updated ↓ saved

These events are useful for:

  • Auditing

  • Search indexing

  • Domain integrations

  • Maintaining related data

  • Triggering application workflows

Example:

User::created(function (User $user) {
    logger()->info('User created', [
        'user_id' => $user->id,
    ]);
});

However, don't put complicated business workflows into model observers just because they are convenient.

For complex workflows, application services or explicit domain events often provide better control.


7. The Hidden Trap: Mass Updates Bypass Model Events

This is one of the most important differences to understand.

Compare:

$user = User::find(1);

$user->status = 'inactive';

$user->save();

With:

User::where('status', 'active')
    ->update([
        'status' => 'inactive',
    ]);

The second example performs a mass database update.

Laravel does not retrieve every affected model and execute its individual saving, updating, updated, and saved events.

Why?

Because the update is performed directly through the database query builder rather than through individual model instances.

This distinction can break assumptions in applications that rely on observers for auditing or synchronization.

Senior-engineer lesson: Never assume that every database update triggers Eloquent model events.


8. Attribute Casting Is More Than Formatting

Consider:

protected function casts(): array
{
    return [
        'is_active' => 'boolean',
        'settings' => 'array',
        'created_at' => 'datetime',
    ];
}

Your database may store JSON or integer values.

But Eloquent exposes them through transformed PHP values.

For example:

$user->settings;

May return a PHP array instead of a raw JSON string.

This is another reason to distinguish between:

$user->getAttributes();
$user->getRawOriginal('settings');
$user->settings;

These methods don't necessarily return the same representation.

Casts, accessors, and mutators form an important part of Eloquent's attribute transformation system.


9. When Eloquent Becomes Expensive

Consider:

$users = User::with([
    'orders',
    'orders.items',
    'profile',
    'permissions',
])->get();

Eager loading solves N+1 queries, but it doesn't automatically make a query efficient.

Potential problems include:

  • Hydrating too many models

  • Loading unnecessary columns

  • Loading huge relationship collections

  • Excessive memory consumption

  • Expensive attribute accessors

  • Over-fetching nested relationships

For large datasets, consider:

User::select(['id', 'name'])
    ->with('orders:id,user_id,total')
    ->chunkById(500, function ($users) {
        // Process a batch.
    });

For read-heavy workloads, also evaluate:

User::query()
    ->select(['id', 'name'])
    ->toBase()
    ->get();

A query-builder result can be more appropriate when you don't need Eloquent model functionality.

Choose the abstraction based on the actual workload.


10. Advanced Eloquent Debugging Techniques

When investigating unexpected SQL execution, these tools are useful:

Query logging:

DB::listen(function ($query) {
    logger()->debug('SQL Query', [
        'sql' => $query->sql,
        'bindings' => $query->bindings,
        'time_ms' => $query->time,
    ]);
});

Inspect relationship loading:

$user->relationLoaded('orders');

Inspect dirty attributes:

$user->getDirty();

Inspect original attributes:

$user->getOriginal();

Inspect generated SQL:

$query = User::where('active', true);

dump($query->toSql());
dump($query->getBindings());

These techniques help you understand what Eloquent is actually doing instead of guessing based on application code.


🧠 The Senior Laravel Developer Mental Model

Don't think:

Eloquent = Convenient Database Queries

Think:

Eloquent ORM
      |
      |-- Query Construction
      |
      |-- Model Hydration
      |
      |-- Attribute Transformation
      |
      |-- Dirty Tracking
      |
      |-- Relationship Management
      |
      |-- Model Event Lifecycle
      |
      |-- Persistence

Eloquent is not just a query wrapper.

It is an object-relational mapping system with its own lifecycle, state management, relationship resolution, and persistence behavior.

Understanding these internals helps you make better architectural decisions and diagnose performance problems at their actual source.


🔥 Advanced challenge for Laravel developers

Consider:

User::where('status', 'active')
    ->update([
        'status' => 'inactive',
    ]);

Which of the following statements are correct?

  1. Every affected User model is hydrated.

  2. The updating event fires for every affected user.

  3. The database performs a mass UPDATE.

  4. Individual model observers are automatically executed for every affected row.

Share your answer in the comments and explain why.

Day 5/25 complete.

Tomorrow:

👉 Laravel N+1 Query Optimization — Beyond with(): Automatic Eager Loading, Query Plans, Indexing, and Detecting Hidden Database Bottlenecks.

Comments

Popular Posts

How to setup phpstorm in windows for laravel

🚀 Day 4 : Advanced Laravel Internals : Middleware Pipeline — What Happens Before AND After Your Controller?