How do I return all the ids of AllSubSections
(all levels)
class Section extends Model
{
public function Ads()
{
return $this->hasMany(Ad::class);
}
public function AllSubSections()
{
return $this->SubSections()->with('AllSubSections');
}
public function SubSections()
{
return $this->hasMany(Section::class);
}
public function Parent()
{
return $this->belongsTo(Section::class);
}
}
what am currently doing is :
$section = Section::where('name', 'Properties')->first();
$subSections = $section->AllSubSections;
$subSections->pluck('id')
but it only returns the 1st level not all the levels.
Here is what I came with:
As you can see, getAllChildren is a recursive function. It contains a loop over the section children that adds to the collection the current child and calls itself again on this child.
You can then use:
And you will get all your children ids.
I hope I am responding to the question!