Add whenRelation to Eloquent relations#60306
Conversation
Add Relation::whenRelation() as a non-breaking alternative to when() for cases where the conditional callback needs the relation instance instead of the forwarded Eloquent builder. The existing when() behavior is preserved so typed callbacks that expect an Illuminate\Database\Eloquent\Builder continue to work. Tests cover the new relation-aware callbacks and the existing forwarded when() callback behavior.
|
First things first, it would have helped me understand this if there was an example in the PR description
Okay, so User::query()->posts()->when(...);doesn't work, right? And now we can do User::query()->posts()->whenRelation(...);as if it was Without this context and by just seeing the method name, I would assume, I would have to write User::query()->whenRelation('posts', ...); |
|
Sorry about that, and thanks for pointing it out. I've updated the description to show that |
|
Thanks for updating to prevent misunderstandings. However, I would find |
|
That makes sense. I see how The intent here is narrower: an opt-in Given that, I agree the current name may be misleading. I'm open to renaming it |
Summary
This adds
whenRelation()to Eloquent relations.This addresses #53292, where calling
when()on a relationship forwards the callto the underlying Eloquent builder instead of passing the relationship instance
to the callback.
The existing
when()behavior is left unchanged so callbacks typed asIlluminate\Database\Eloquent\Buildercontinue to work.Fixes #53292.
Tests
whenRelation()callbacks receiving the relation instance.when()continues to receive the underlying builder.