samedi 7 mars 2020

Laravel Recursion In Controller

I am trying to get all of a Boards decendants and change their category ID based on a request from the view. I am currently running multiple foreach statements in my controller but I would like their to only be one foreach statement.

Format

Board 1
- Board 2
-- Board 3
--- Board 4

Here is my Model:

public function children()
{
    return $this->hasMany(Board::class, 'parent_id');
}

public function listChildren()
{
    $sections = new Collection();
    foreach($this->children as $section) {
        $sections->push($section);
        $sections = $sections->merge($section->listChildren());
    }
    return $sections;
}

An Image of how my collection is formatted by the above: collection

And my Controller:

foreach($board->listChildren() as $cboard) {
    foreach($cboard->listChildren() as $ccboard) {
        $ccboard->category_id = request('category_id');
        $ccboard->save();
    }
    $cboard->category_id = request('category_id');
    $cboard->save();
}

How would I go about doing this? Thank you for your help!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire