Recursively generating heading numbers
Generating heading numbers for a recursive structure in Laravel using attribute accessors

For the Mijn Koepelkerk project I needed to create a page that would show all the organizational information like key figures, statutes, official stances on specific topics, and so forth. Each item is either a root item or a child item. The child items can have child items themselves. This is a recursive structure, which meant I could easily generate header numbers and depth.
/**
* The heading number including super-items. E.g.: "1.1".
*/
protected function headingNumber(): Attribute
{
return Attribute::get(fn(): string => !$this->parent
? "$this->sort_index"
: "{$this->parent->heading_number}.{$this->sort_index}"
);
}
/**
* How many levels this item is, starting at 1.
*/
protected function depth(): Attribute
{
return Attribute::get(fn(): int => 1 + ($this->parent?->depth ?? 0));
}
This makes use of Laravel’s attribute accessors to create computed properties, which can then be accessed like any other property.
Reflection
A WYSIWYG1 editor like CKEditor could have been a less complex option, with the downside that if you want to make any change in the structure of the page, you were going to have to re-number all the headings manually, as I don’t know of any easily integrated WYSIWYG editors that support auto numbering of headings.
What You See Is What You Get ↩︎