How do I get all children that fall under a parent in eloquent?
This way works very good:
class One extends Model {
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
public function grandchildren()
{
return $this->children()->with('grandchildren');
}
}
After hoping to find an answer that uses Laravel nicely, I ended up giving up and just writing the code to do what I wanted myself, and it ended up smaller than I anticipated.
public function all_products()
{
$products = [];
$categories = [$this];
while(count($categories) > 0){
$nextCategories = [];
foreach ($categories as $category) {
$products = array_merge($products, $category->products->all());
$nextCategories = array_merge($nextCategories, $category->children->all());
}
$categories = $nextCategories;
}
return new Collection($products); //Illuminate\Database\Eloquent\Collection
}