🚀 Proposal: Add withExtra() to JsonResource for Clean Inline Augmentation #55644
Unanswered
slisarenko
asked this question in
Ideas
Replies: 1 comment
-
Can't this be achieved already with appends on the model and/or with relations on the model? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
✨ Summary
I propose adding a
withExtra()
method to Laravel’sIlluminate\Http\Resources\Json\JsonResource
class. This method would allow developers to append additional top-level data to a resource response in a clean, expressive, and reusable way — without overriding the existingwith()
method or manually modifying the array intoArray()
.💡 Motivation
While Laravel already supports attaching data via the
with()
method, its behavior is limited:meta
key, which is ideal for metadata, but not for enriching the resource directly.There are many cases where developers want to add more fields to the top level of a resource’s JSON structure. This could include:
📦 Example Use Case
Let’s say we're returning a
UserResource
. By default, it includes basic data. In some responses, we want to include permissions and a JWT token at the top level.✅ Controller
✅ Resource
📤 Expected JSON Output
🤔 Why Not Use
with()
?The existing
with()
method works well for metadata — but it’s not suitable for inline data injection:with()
withExtra()
(Proposed)meta
only🛠 Implementation Summary
To implement this behavior, the following minimal additions are proposed to
JsonResource
:1. Add an
$extra
property2. Add the
withExtra()
method3. Update the
resolve()
method✅ Benefits
Beta Was this translation helpful? Give feedback.
All reactions