class Category extends Model {
// Each category may have one parent
public function parent() {
return $this->belongsToOne(static::class, 'parent_id');
}
// Each category may have multiple children
public function children() {
return $this->hasMany(static::class, 'parent_id');
}
}
Category::with('children')
->whereNull('category_id')
->orderBy('name', 'asc')
->get());