Faustas Butkus
Faustas Butkus

Reputation: 311

Laravel recursive relations and returning $this

I have navbar with unknown levels of industries which can have child industries and I want to write recursive relationship to get the top one and show it as Category. I tried this:

public function category()
{
    if($this->parent_id == 0){
        return $this;
    } else {
        $this->parent_industry->category();
    }
}

But I keep getting LogicException: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

How to write recursive relationship and return $this?

Upvotes: 5

Views: 2923

Answers (2)

FULL STACK DEV
FULL STACK DEV

Reputation: 15941

Hi you can do this in an easy rather than using while

public function children()
{
   return $this->hasMany('App\MenuItem', 'parent_id');
}

public function parent()
{
   return $this->belongsTo('App\MenuItem', 'parent_id');
}

public function root()
{
    if ($this->parent)
        return $this->parent->root();

    return $this;
}

Using recursion it is much simpler.

Hope this helps.

Upvotes: 1

akaincore
akaincore

Reputation: 331

Try this relations:

public function children()
{
    return $this->hasMany('App\MenuItem', 'parent_id');
}

public function parent()
{
    return $this->belongsTo('App\MenuItem', 'parent_id');
}

public function getRoot()
{
    $cur = $this;
    while ($cur->parent) {
        $cur = $cur->parent;
    }
    return $cur;
}

Upvotes: 5

Related Questions