Hydration & dehydration — mapping raw data into typed objects and back
Definition
Hydration is the process of mapping raw, unstructured data (a database row, a JSON payload, an array) into a typed object whose properties have meaning within your domain. Dehydration is the reverse: serializing a typed object back into a primitive representation suitable for storage or transport. The word "hydration" comes from the idea of breathing life into a flat data structure — turning a row into an entity that has behavior, validation, and type guarantees.
In Practice
<?php
// Raw data arriving from a database query
$row = [
'id' => 42,
'name' => 'Ada Lovelace',
'email' => 'ada@example.com',
'created_at' => '2024-01-15 09:00:00',
];
// Hydration: map the raw row into a typed domain object
class User
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $email,
public readonly \DateTimeImmutable $createdAt,
) {}
public static function hydrate(array $row): self
{
return new self(
id: (int) $row['id'],
name: $row['name'],
email: $row['email'],
createdAt: new \DateTimeImmutable($row['created_at']),
);
}
// Dehydration: serialize back to a primitive array
public function dehydrate(): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->createdAt->format('Y-m-d H:i:s'),
];
}
}
$user = User::hydrate($row);
echo $user->createdAt->format('d M Y'); // "15 Jan 2024" — typed, not a string
// Dehydrate before saving
$rowToSave = $user->dehydrate();Laravel's Eloquent ORM performs hydration automatically when you call User::find(1) — it takes the PDO result row and populates model attributes. When you call $user->toArray() or $user->toJson(), it dehydrates. Understanding this cycle explains why Eloquent models are not plain arrays and why their attribute types depend on casts you define.
In Context
In technical interviews, "hydration" is often asked as a follow-up to ORM questions. The interviewer wants to confirm you understand that a model is not the same as a database row — the ORM mediates between two representations and that mediation has a cost (memory, CPU, object construction). Knowing this word signals you understand what ORMs actually do.
A common misconception is that hydration is an ORM-specific concept. It is not. Any time you deserialize data into a typed object — from a cache hit, a message queue payload, an API response — you are performing hydration. Symfony's Serializer component, Laravel Data, and Spatie's Data packages all make hydration explicit and configurable.
The related term "mapping" is often used interchangeably, but "mapping" is broader (any transformation between structures) while "hydration" specifically implies populating an existing object type from raw data. "Deserialization" is similar but implies a serialization format (JSON, XML, binary) was involved; hydration can happen from any source, including plain PHP arrays.