🚀 Proposal: Add withExtra() to JsonResource for Clean Inline Augmentation #55644
-
✨ SummaryI propose adding a 💡 MotivationWhile Laravel already supports attaching data via the
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 CaseLet’s say we're returning a ✅ Controllerpublic function show(Request $request, User $user): JsonResponse
{
return UserResource::make($user)
->withExtra([
'permissions' => $user->getPermissions(),
'token' => $request->user()?->createToken('access')->plainTextToken,
])
->toResponse($request);
} ✅ Resourceclass UserResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
} 📤 Expected JSON Output{
"id": 1,
"name": "Jane Doe",
"email": "jane@example.com",
"permissions": ["read", "write"],
"token": "abc123..."
} 🤔 Why Not Use
|
Feature | with() |
withExtra() (Proposed) |
---|---|---|
Shown on nested resources? | ❌ No | ✅ Yes |
Appears at top-level JSON? | ❌ Inside meta only |
✅ Merged with main payload |
Ideal for payload fields? | ❌ Not really | ✅ Yes |
Target use case | Metadata | Resource enrichment |
🛠 Implementation Summary
To implement this behavior, the following minimal additions are proposed to JsonResource
:
1. Add an $extra
property
protected array $extra = [];
2. Add the withExtra()
method
public function withExtra(array $extra): static
{
$this->extra = array_merge($this->extra, $extra);
return $this;
}
3. Update the resolve()
method
public function resolve($request = null)
{
$data = $this->toArray(
$request = $request ?: Container::getInstance()->make('request')
);
if ($data instanceof Arrayable) {
$data = $data->toArray();
} elseif ($data instanceof JsonSerializable) {
$data = $data->jsonSerialize();
}
return $this->filter(array_merge((array) $data, $this->extra));
}
✅ Benefits
- ✅ Cleaner developer experience
- ✅ Less boilerplate
- ✅ Works consistently even when nested
- ✅ No breaking changes — fully opt-in
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
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.
#55695