wt0f's avatar
Level 1

Is it possible to have hasMany in memory?

I have an Eloquent model that uses MongoDB as the backend. This model stores information on PBXes and part of the model is an array of trunk information. Today I am treating the trunk information as an array and that is becoming a bit of a pain as I am finding more needs to validate and insure that the trunk information has some specific attributes.

I then started to think that it would be better if I created a trunk model that would manage and insure that the attributes were present or set rational default values. This would make the PBX model have a hasMany relationship with the trunk model.

But here is the rub. I don't want to have the trunk model be another collection in MongoDB. It is already a subset of the PBX model / collection. What I am really looking for (ideally) is if when reading a PBX record that the trunk array could be "de-serialized" into an in-memory array of trunk objects (via the model) and then when the PBX model is saved that the the trunk objects would then be "serialized" back into the PBX model to be saved.

It would be great if it would be automatic like this, but I suspect that I would need to write some code around this process. I just don't know any of the innards of Eloquent to know how I could intercept the calls and make something like this work.

I have only been using Laravel for a few weeks and still learning things every day. If anyone has any ideas, I would love to hear them.

Thanks, Gerard.

0 likes
4 replies
wt0f's avatar
Level 1

That looks pretty interesting and may be helpful, but there is still a couple questions in my mind concerning how to hook it in. Are there any hooks or special functions that are called just after retrieving data from the DB (such as at the completion of get() or where()) or just before the save() operation is done?

wt0f's avatar
Level 1

In digging around a bit more I found the following: (ARG, Laracasts will not allow me to post URLs) laravel.com/docs/8.x/eloquent-mutators#custom-casts

It seems like it might be what I am looking for. I am just wondering if someone with better knowledge can save me some time if custom casts would not work for my situation.

Snapey's avatar

@wt0f you can hook into events which are fired as the record is being updated, created etc

Please or to participate in this conversation.