Skip to content
Advertisement

Laravel collection multi level groupBy insert new items without checking each level’s key

Laravel collections now have a great multi-level groupBy function built in, but I am struggling with a sensible way to insert new items.

For example:

JavaScript

Very nice, easy to set up and access. For this example, I will assume each key is a number

JavaScript

If there are already items in the nested positions [1], [2], and [3] then I can add a new item or overwrite the existing item at [4], but if any of the nested positions 1 through 3 is missing I get an error

JavaScript

At the moment I am calling an insert into structure function with:

JavaScript

I find the groupBy nesting very useful, apart from not handling my inserts cleanly.

Some sample data – please assume there are > 100k records like this:

JavaScript

Instead of username and course in real life it would be a code representing that specific user and that course.

The data would include minutes of activity, counts of activity, grade of activity, how early or late the activity was etc.

Advertisement

Answer

I think you could extend the collection, adding a custom insertDeep function.

An idea:

JavaScript

Then you could simply call this method on your collection:

JavaScript

I just tried it and it should work properly:

JavaScript

Disclaimer: this function will fail if you specify a path where a key already exists but whose value is not a collection

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement