Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
Faustas Butkus Avatar asked Jan 25 '18 17:01

Faustas Butkus


2 Answers

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;
}
like image 92
akaincore Avatar answered Nov 03 '22 23:11

akaincore


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.

like image 1
Romantic Dev Avatar answered Nov 03 '22 23:11

Romantic Dev