Pre processing listed records of a resource

I have create a resource which is based on a Page model. I want to show the pages in their parent child hierarchy. I have found next solution to do so in regular Laravel. But can not find the correct way to do this so I can use it in a Filament list of resources. Optionally I want to allow the filament sorting options within the hierarchy sorting:

$pages = Page::all();

        $generator = function (Collection $level, $prefix = '') use ($pages, &$generator) {
            // here we are sorting by 'id', but you can sort by another field
            foreach ($level->sortBy('id') as $item) {
                // yield a single item
                yield $item;


                //$item->level = $level->count();

                if($prefix != '')
                {
                    $item->title = $prefix . ' ' . $item->title;
                }
    
                // continue yielding results from the recursive call
                yield from $generator($pages->where('parent_id', $item->id ), $prefix . '— ');
            }
        };
    
        $results = LazyCollection::make(function () use ($pages, $generator) {
            // yield from root level
            $prefix = '';

            yield from $generator($pages->where('parent_id', null), $prefix);
        })->flatten()->collect();

        return $results->toJson();
Was this page helpful?