Improve JsonResource to Respect Selected Columns and Exclude Unselected Model Attributes #56051
Replies: 2 comments
-
@MudassirAmeen this is in fact an interesting finding that we would label as bug. But, maybe for consistency in responses to not break some clients that rely on the keys being there, it is not a bug but a feature. If you want this functionality you can use our crud lib free suite. |
Beta Was this translation helpful? Give feedback.
-
@macropay-solutions Thanks for the response! I agree it’s important not to break client-side expectations. My suggestion was more towards having this behavior optionally enabled — either via a trait or a setting. In the meantime, I’ve implemented a reusable base resource that only includes selected columns and loaded relationships. Sharing this with the community might help others who prefer cleaner responses without unnecessary |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
When using Laravel’s
JsonResource
, all model attributes are included in the API response — even if the Eloquent query only selected a subset of columns using->select(...)
.This causes unexpected or unnecessary fields to appear in the final JSON. Consider:
The above will still output all columns (
email
,created_at
, etc.) if they exist in the model, becauseJsonResource
accesses model properties directly (using$this->attribute
or$this->{$key}
), bypassing the original selection intent.🎯 Why This Matters
✅ Current Workaround
To solve this, I implemented a custom BaseResource that ensures only selected attributes and loaded relationships are included in the response:
Then you can define a concrete resource like this:
💡 Feature Suggestion
Laravel could offer an optional feature or trait like:
Or even an enhancement in
JsonResource
to respect$model->getAttributes()
by default rather than directly accessing$this->{$key}
blindly.📌 Why Not Just Remove All Nulls?
We should not remove all null values — some are intentionally returned to the frontend to indicate "present but empty."
The goal is to exclude only the attributes that were never selected or loaded, not to cleanse all nulls.
🤝 Conclusion
This would make Laravel’s
JsonResource
system cleaner and smarter by design.I’d love to hear community feedback on whether something like this could become part of the core, or possibly provided as a supported trait or helper.
Thanks for the great framework and community support! Love Laravel ❤️
Beta Was this translation helpful? Give feedback.
All reactions