Dinesh Uprety
@dineshuprety ·
Public
Hydrate eager-loaded parents on children
PHPLaravel 12: prevent child-to-parent N+1 queries with chaperone(). Source: laravel.com/docs/12.x/eloquent-relationships
Remixed from Find the first matching array value
PHP
CodeSnap // free canvas
Hydrate eager-loaded parents on children
<?php
use Illuminate\Database\Eloquent\Relations\HasMany;
public function comments(): HasMany
{
return $this->hasMany(Comment::class)->chaperone();
}
// $comment->post is already hydrated after eager loading.
Compare with original
Original · Find the first matching array value
<?php
$admin = array_find(
$users,
static fn (User $user): bool => $user->isAdmin(),
);
// $admin is the first match, or null.
This remix · Hydrate eager-loaded parents on children
<?php
use Illuminate\Database\Eloquent\Relations\HasMany;
public function comments(): HasMany
{
return $this->hasMany(Comment::class)->chaperone();
}
// $comment->post is already hydrated after eager loading.