Fresh code drop

Hydrate eager-loaded parents on children

PHP

Laravel 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.

Turn your code into a post.Five templates are free—no account needed.

Remix this snap