*/ use HasFactory; protected static function booted(): void { static::creating(function (Category $category) { if (empty($category->slug)) { $category->slug = Str::slug($category->name); } }); } /** * @return BelongsTo */ public function parent(): BelongsTo { return $this->belongsTo(Category::class, 'parent_id'); } /** * @return HasMany */ public function children(): HasMany { return $this->hasMany(Category::class, 'parent_id'); } /** * @return HasMany */ public function posts(): HasMany { return $this->hasMany(Post::class); } /** * @return Collection */ public function ancestors(): Collection { $ancestors = collect(); $category = $this->parent; while ($category !== null) { $ancestors->prepend($category); $category = $category->parent; } return $ancestors; } }