$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[March 09, 2025] Eloquent ORM

Eloquent Model Hydrators: Raw Data

Eloquent Model Hydrators: Raw Data

────────────────────────────────────────────────────────

Eloquent Model Hydrators: Raw Data

Tip: hydrate() Method

$posts = Post::hydrate($rawData);

Creates model instances without database queries.

Gotcha: Hydrated Models Are Not Saved

Hydrated models exist in memory only. Call save() to persist.

Tip: newFromBuilder()

$post = (new Post)->newFromBuilder($rawData);

Creates a model from raw data, marking it as existing.

Gotcha: fill() vs hydrate()

fill() sets attributes on an existing model. hydrate() creates new instances from an array.

Tip: make() for Unsaved Models

$post = Post::make(['title' => 'Test']);

Gotcha: Casting on Hydrated Models

Casts and accessors work on hydrated models just like database-fetched ones.

Tip: Use cursor() for Memory-Neutral Iteration

When exporting 100K rows, get() loads everything into memory. cursor() uses yield and keeps memory flat regardless of row count. Perfect for artisan commands.

Tip: whereHas() vs load() — Two Different Things

whereHas() filters the parent query by relationship existence. load() eager-loads relationships AFTER the query. Mixing them up is a common source of logic bugs.

Gotcha: withCount() Adds a Subquery

withCount('comments') runs a correlated subquery on every row. On large tables, this can be slower than a separate query. Profile before relying on it.

Senior Insight

The most impactful Eloquent optimization I've made is enabling strict() mode in Laravel 8+. It prevents lazy loading, adds performance warnings, and catches unguarded attributes. Most teams discover lazy loading problems in production under load. With preventLazyLoading() enabled, you catch them in development. This single configuration change has prevented more production incidents than any other Laravel setting I've encountered.

Source: Laravel Docs (https://laravel.com/docs/eloquent), Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/eloquent)

────────────────────────────────────────────────────────
<-- back to posts