Skip to content

Infinite loop problem on laravel livewire #604

Open
@ozgurzurnaci

Description

@ozgurzurnaci

I'm trying to create a nested tree category system in laravel livewire. My livewire component codes:

app/Livewire/CategoryTree.php:


use Livewire\Component;
use App\Models\Category;

class CategoryTree extends Component
{
public $categories;
public $newCategoryName = '';
public $parentId = null;

protected $listeners = ['updateOrder' => 'updateOrder'];

public function mount()
{
    $this->categories = Category::get()->toTree();
}

public function render()
{
    return view('livewire.category-tree', ['categories' => $this->categories]);
}

public function addCategory()
{
    $this->validate([
        'newCategoryName' => 'required|string|max:255',
    ]);

    $parent = Category::find($this->parentId);
    $category = new Category(['name' => $this->newCategoryName]);

    if ($parent) {
        $parent->appendNode($category);
    } else {
        Category::create(['name' => $this->newCategoryName]);
    }

    $this->resetForm();
    $this->mount();  // Kategorileri yeniden yükle
}

public function deleteCategory($id)
{
    $category = Category::findOrFail($id);
    $category->delete();
    $this->mount();  // Kategorileri yeniden yükle
}

public function updateOrder($order)
{
    $this->saveOrder($order);
    $this->categories = Category::get()->toTree();
}

private function saveOrder($order, $parentId = null)
{
    foreach ($order as $index => $item) {
        $category = Category::find($item['id']);
        $category->parent_id = $parentId;
        $category->save();

        if (isset($item['children'])) {
            $this->saveOrder($item['children'], $item['id']);
        }
    }

    Category::fixTree();  // lft, rgt, depth değerlerini otomatik olarak düzeltir
}

private function resetForm()
{
    $this->newCategoryName = '';
    $this->parentId = null;
}
}

app/Model/Category.php:


namespace App\Models;
use Kalnoy\Nestedset\NodeTrait;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
use NodeTrait;

protected $fillable = ['name', 'parent_id'];
}

this line cause the problem:
$this->categories = Category::get()->toTree();
when i use the toTree() function, laravel gives this error:
the error is "Xdebug has detected a possible infinite loop, and aborted your script with a stack depth of '512' frames"

if i use toFlatTree() function, script runs without error and i can see Categories.

i have to list categories in tree format. how can i fix this problem?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions