$ lexprog.com

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

[May 25, 2026] Eloquent ORM

Eloquent Model Serialization: Custom

Eloquent Model Serialization: Custom

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

Eloquent Model Serialization: Custom

Tip: toArray() Override

public function toArray(): array
{
    return [
        'id' => $this->id,
        'title' => $this->title,
        'author' => $this->author->name,
    ];
}

Gotcha: makeHidden()

$user->makeHidden(['password', 'remember_token']);

Tip: makeVisible()

$user->makeVisible(['created_at']);

Shows hidden attributes for this serialization only.

Gotcha: $hidden Property

protected $hidden = ['password', 'remember_token'];

Always hidden from serialization.

Tip: $visible Property

protected $visible = ['id', 'title', 'content'];

Only these fields are serialized.

Gotcha: serializeDate()

protected function serializeDate(DateTimeInterface $date): string
{
    return $date->format('Y-m-d');
}

Custom date format for all serialized dates.

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

Model serialization is where the 'leaky abstraction' of Eloquent becomes most apparent. I've seen models serialized with ->toArray() that exposed internal attributes never meant for API consumption. Using API Resources with explicit toArray() methods gives you control over what's exposed. And always use Resource::collection() for lists — it provides a consistent data envelope and makes pagination integration straightforward.

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

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