Skip to content

List Structure ​

The ListStructure widget is a list that shows parent and child records as a tree and reorders them by dragging. It takes every list option, adds its own, and saves each move to the model: a tree model gets its new parent, and a sortable model stores the new order. It shows every record at once, without pages, until a header sorts it.

Tree ​

The categories here are a plain Eloquent model that implements TreeInterface, where each category names its parent in a parent_id column and keeps its place in a sort_order column. Drag a row up or down to reorder it, or to the right to nest it under the row above, down to maxDepth levels. The arrows expand and collapse a branch, and the list remembers each branch for the session.

Sorting by a header or searching shows a flat list. After a sort, the "Show tree" button at the end of the header, or a third click on the same header, brings the tree back; a flat reorderable list's button reads "Show order". After a search, clearing the search brings it back. The toolbar's search box is bound to the tree the same way as to any list, and looks in its searchable columns.

php
/**
 * makeTreeList shows the categories as a tree that drags three levels deep at most.
 */
protected function makeTreeList(): ListStructure
{
    return ListStructure::make(
        alias: 'treeList',
        model: new Category,
        columns: '~/resources/ui/reference/lists/list-structure/categories.yaml',
        maxDepth: 3,
    );
}

/**
 * makeTreeToolbar has the search box that searches the given tree.
 */
protected function makeTreeToolbar(ListStructure $list): Toolbar
{
    $toolbar = Toolbar::make(
        alias: 'treeToolbar',
        search: ['prompt' => 'Search categories...'],
    );

    $toolbar->bindToListWidget($list);

    return $toolbar;
}
yaml
columns:
    name:
        label: Category
        searchable: true

    slug:
        label: Slug
        searchable: true

    posts_count:
        label: Posts
        type: number
        relation: posts
        relationCount: true
php
/**
 * Category is a post category stored as a simple tree, where each category points at its parent and keeps its place among its siblings in a sort order column.
 */
#[Fillable(['name', 'slug', 'description', 'parent_id'])]
class Category extends Model implements SortableInterface, TreeInterface
{
    /** @use HasFactory<CategoryFactory> */
    use HasFactory;

    /**
     * parent is the category this one sits below, or null at the top level.
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    /**
     * children are the categories directly below this one, in their sort order.
     */
    public function children(): HasMany
    {
        return $this->hasMany(Category::class, 'parent_id')->orderBy('sort_order');
    }

    /**
     * getChildren returns the categories directly below this one, nested in memory by getNested.
     */
    public function getChildren(): Collection
    {
        return $this->children;
    }

    /**
     * getChildCount returns the number of categories anywhere below this one.
     */
    public function getChildCount(): int
    {
        return $this->getAllChildren()->count();
    }

    /**
     * scopeGetNested returns the top level categories of the query with their children nested below them, leaving out categories whose parent the query skipped.
     */
    public function scopeGetNested($query): Collection
    {
        $categories = $query->orderBy('sort_order')->get()->keyBy('id');

        foreach ($categories as $category) {
            $category->setRelation('children', $category->newCollection());
        }

        $roots = $this->newCollection();

        foreach ($categories as $category) {
            if (!$category->parent_id) {
                $roots->push($category);
            }
            elseif ($parent = $categories->get($category->parent_id)) {
                $parent->children->push($category);
            }
        }

        return $roots;
    }

    /**
     * scopeListsNested returns the column values keyed by the key column, in tree order and indented by depth.
     *
     * @return array<int|string, string>
     */
    public function scopeListsNested($query, $column, $key = null, $indent = '&nbsp;&nbsp;&nbsp;'): array
    {
        $result = [];

        $addCategories = function (Collection $categories, int $depth) use (&$addCategories, &$result, $column, $key, $indent) {
            foreach ($categories as $category) {
                $label = str_repeat($indent, $depth).$category->{$column};

                if ($key === null) {
                    $result[] = $label;
                }
                else {
                    $result[$category->{$key}] = $label;
                }

                $addCategories($category->getChildren(), $depth + 1);
            }
        };

        $addCategories($query->getNested(), 0);

        return $result;
    }

After a drop, the list associates the category's parent relation with its new parent, and passes setSortableOrder() the ids of every row in their new order, as sort_orders:

php
/**
 * setSortableOrder stores a new order for the given categories, numbered from one unless the orders are supplied.
 *
 * @param  array<int, int|string>  $itemIds
 * @param  array<int, int>|bool|null  $itemOrders
 */
public function setSortableOrder($itemIds, $itemOrders = null): void
{
    if (!is_array($itemIds)) {
        return;
    }

    $itemIds = array_values($itemIds);
    $orders = is_array($itemOrders) && count($itemOrders) === count($itemIds)
        ? array_values($itemOrders)
        : range(1, count($itemIds));

    foreach ($itemIds as $index => $id) {
        static::query()->whereKey($id)->update(['sort_order' => $orders[$index]]);
    }
}

Tree with checkboxes ​

showCheckboxes: true puts a checkbox before each row, and the drag handle beside it, so the tree can be both reordered and worked on. Shift and click checks a run of rows, as in any list. A toolbar button with checked: true sends the ids of the checked rows as checked, and is disabled while none are checked.

php
/**
 * makeCheckboxTree adds a checkbox to each row of the tree, which still reorders by dragging.
 */
protected function makeCheckboxTree(): ListStructure
{
    return ListStructure::make(
        alias: 'checkboxTree',
        model: new Category,
        columns: '~/resources/ui/reference/lists/list-structure/categories.yaml',
        showCheckboxes: true,
        maxDepth: 3,
    );
}

/**
 * makeCheckboxTreeToolbar has a button that sends the checked rows of the given tree.
 */
protected function makeCheckboxTreeToolbar(ListStructure $list): Toolbar
{
    $toolbar = Toolbar::make(
        alias: 'checkboxTreeToolbar',
        buttons: [
            'show' => [
                'label' => 'Show checked',
                'icon' => 'ph ph-list-checks',
                'handler' => 'onShowCheckedCategories',
                'checked' => true,
                'attributes' => ['data-request-flash' => true],
            ],
        ],
    );

    $toolbar->bindToListWidget($list);

    return $toolbar;
}

/**
 * onShowCheckedCategories names the categories checked in the tree, as sent by the toolbar button.
 */
public function onShowCheckedCategories(): AjaxResponse
{
    $names = Category::whereIn('id', (array) request()->input('checked'))->orderBy('name')->pluck('name');

    return ajax()->flash('info', $names->count().' '.Str::plural('category', $names->count()).' checked: '.$names->implode(', ').'.');
}

Browsing tree ​

treeExpanded: false starts with every branch closed, and showReorder: false removes the drag handles, leaving a tree to browse. permissions does the same for visitors without one of the named gate abilities: they see no handles, and a reorder request from them is refused.

php
/**
 * makeBrowseTree starts with the branches closed and offers no reordering.
 */
protected function makeBrowseTree(): ListStructure
{
    return ListStructure::make(
        alias: 'browseTree',
        model: new Category,
        columns: '~/resources/ui/reference/lists/list-structure/categories.yaml',
        treeExpanded: false,
        showReorder: false,
    );
}

Reorderable list ​

showTree: false reorders a flat list, for a model that implements October\Contracts\Database\SortableInterface, like the users here. After a drop, the list posts the ids of every row in their new order as sort_orders, and calls the model's setSortableOrder() with them. Until a header sorts the list, the rows are ordered by the sortOrderColumn, sort_order by default.

dragRow: false drags a row by its handle only, so the rows can still be selected and clicked.

php
/**
 * makeReorderList shows the users as a flat list, dragged by the handle into a new order.
 */
protected function makeReorderList(): ListStructure
{
    return ListStructure::make(
        alias: 'reorderList',
        model: new User,
        columns: '~/resources/ui/reference/lists/list-structure/users.yaml',
        showTree: false,
        dragRow: false,
    );
}
yaml
columns:
    name:
        label: Name

    email:
        label: Email

    sort_order:
        label: Order
        type: number
php
/**
 * Persist a new record ordering. Called by the ListStructure widget when
 * rows are dragged into a new order.
 *
 * @param  array<int, int|string>  $itemIds
 * @param  array<int, int>|null  $itemOrders
 */
public function setSortableOrder($itemIds, $itemOrders = null): void
{
    if (! is_array($itemIds)) {
        return;
    }

    foreach (array_values($itemIds) as $index => $id) {
        static::withoutEvents(function () use ($id, $index) {
            static::query()->whereKey($id)->update(['sort_order' => $index + 1]);
        });
    }
}

Model requirements ​

  • A tree, the default, needs a model that implements October\Contracts\Database\TreeInterface, with getChildren(), getChildCount() and the getNested() and listsNested() scopes, like the categories above. Any other model throws an error that suggests showTree: false. See trees for what each method returns.
  • A move is saved in the ways the model supports. A model that implements NestedSetInterface moves the node next to its new neighbour or under its new parent. Otherwise, a model with a parent relation gets its new parent, and a model that implements SortableInterface gets its new order through setSortableOrder(). A model with none of these shows the drag handles but keeps its order.
  • A flat reorderable list works on any model that implements SortableInterface, with a sort_order column and its own setSortableOrder(), like the users above.

Structure and sorting ​

The structure and column sorting do not mix. Clicking a sortable header hides the tree and sorts a flat list, with pages when recordsPerPage is set, and a third click on the same header brings the structure back, as does the icon at the end of the header. Searching also shows flat results until the search is cleared. A list with a defaultSort starts sorted and flat, until the visitor brings the structure back.

Options ​

ListStructure::make() takes every list option and these.

OptionDescription
showTreeshows the parent and child records as a tree. Default: true.
treeExpandedstarts with every branch open. The state of each branch is kept in the session. Default: true.
showReordershows a drag handle on each row. Default: true.
maxDepththe most levels a row can be nested by dragging. Default: no limit, or 1 with showTree: false.
dragRowlets the whole row drag, not only its handle. Default: true.
permissionsgate abilities needed to reorder, as a string or an array where any one is enough. Without them the handles are hidden.
sortOrderColumnthe column that orders a flat list while no header sorts it. Default: sort_order.
includeSortOrdersposts sort_orders with every move, which a sortable model always does. Default: false.
includeReferencePoolpasses setSortableOrder() no orders, so the model can share out the current sort orders of the moved rows in place of numbering them from 1, for reordering a subset such as one page. Default: false.
expandLastColumnwhile the list is flat, stretches the last column over the empty cell kept for the handles. Default: false.