Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mahmoud04's avatar

Make category tree

have a task to make category tree I don't no how many parent or children add

example:

- Parent 1
	- children 1
		- children 5
			- children 8
	- children 6
-Parent 2

in Service Provider use Model::shouldBeStrict();

when use filamentphp ineed to display like this:

Parent 1 > children 1 > children 5 > children 8

ok, really I don't have any idea to do this I try many way but still failed

Model:

 protected $fillable = [
        'name',
        'status',
        'parent_id',
        'sort',
    ];

    public function children(): HasMany
    {
        return $this->hasMany(related: self::class, foreignKey: 'parent_id');
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(related: self::class, foreignKey: 'parent_id');
    }
0 likes
2 replies
Snapey's avatar

Change your category to have a category_id column instead of a parent_id column

parent relationship is a belongsTo, you should not need to specify the key

categories relationship is a hasMany, you should not need to specify the key

Eager load like

$tree = Category::with('category.category.category')->whereNull('category_id');

(if you support up to three children)

Please or to participate in this conversation.