laravel-nestedset icon indicating copy to clipboard operation
laravel-nestedset copied to clipboard

The 'parent' relationship missing in Model toJson()

Open saskaak opened this issue 4 years ago • 2 comments

Copypasted from another issue:

The fix you provided makes impossibile to call parent relationship in toArray() or toJson() methods.... is there any official workaround for this? Or at least it should be clearly stated in the docs...Spent a hour debugging this, it's a major problem imho

Originally posted by @Silentscripter in https://github.com/lazychaser/laravel-nestedset/issues/17#issuecomment-284152396

saskaak avatar May 06 '21 19:05 saskaak

A workaround that worked for my use case:

$categories = Category::get()
    ->linkNodes()
    ->map(fn($category) => collect($category)->merge([
        'parent' => $category->parent->uuid ?? null,
    ]));

With this I get a flat collection of all categories and each category has key parent with just the UUID. The trick is to call collect($category), which unsets the parent key, and then add it back using merge().


It would be nice if this was documented somewhere. It took a non-trivial amount of debugging for me to figure this out.

saskaak avatar May 07 '21 08:05 saskaak

is this fixed? I think this is still is an issue

sawirricardo avatar May 17 '22 07:05 sawirricardo