laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Append at runtime on eager loaded relations using with() #2484

Closed dionysiosarvanitis closed 3 years ago

dionysiosarvanitis commented 3 years ago

Feature submitted by @jessarcher with https://github.com/laravel/framework/pull/33422 is really useful!

It would be more useful if we could append at runtime on eager loaded relations instead of the model itself. Tried to do the following but appends array seems to be overridden. Is this intended behaviour?

UserResource::collection(
    User::with([
        'profile' => fn ($q) => $q->getModel()->append('given_name'),
    ])->get()
);

Off course, a possible workaround would be to append on the query result like below but it adds overhead with no reason.

UserResource::collection(
    User::with([
        'profile' => fn ($q) => $q->getModel()->append('given_name'),
    ])->get()->map(fn (User $item) => tap($item, fn($item) => $item->profile->append('given_name')))
themsaid commented 3 years ago

Feel free to submit a PR with your suggested changes.