Eloquent API Resources are the answer you need here rather than returning the Model directly.
Is it possible to modify toArray on the fly?
I have a model with a pre-defined toArray method. The array is made of fields to always be present for this model. From the controller, I just return the model and the serializer converts that array to JSON. However, I have one endpoint that runs a bunch of queries culminating in a with/withCount and loads a certain field that needs to be present for that endpoint alone. When inspected, that value exists on the model, but the moment it undergoes the response rendering process, it vanishes.
I have tried makeVisible and append, among other attempts. But it never attaches. What I resorted to to save time is to include that field in the toArray even though it's only ever going to be used once. Is there no way to dynamically include a field at runtime that would be rendered alongside everything the regular toArray?
Please or to participate in this conversation.