Skip to content

Instantly share code, notes, and snippets.

@brunocmoraes
Created August 9, 2020 20:14
Show Gist options
  • Save brunocmoraes/160567d00f944f9f083a324101d5c002 to your computer and use it in GitHub Desktop.
Save brunocmoraes/160567d00f944f9f083a324101d5c002 to your computer and use it in GitHub Desktop.
Eloquent: Recursive hasMany Relationship with Unlimited Subcategories
<ul>
@foreach ($categories as $category)
<li>{{ $category->name }}</li>
<ul>
@foreach ($category->childrenCategories as $childCategory)
@include('subcategories', ['child_category' => $childCategory])
@endforeach
</ul>
@endforeach
</ul>
<?php
class Category extends Model
{
public function categories()
{
return $this->hasMany(Category::class);
}
public function childrenCategories()
{
return $this->hasMany(Category::class)->with('categories');
}
}
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedBigInteger('category_id')->nullable();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
<li>{{ $child_category->name }}</li>
@if ($child_category->categories)
<ul>
@foreach ($child_category->categories as $childCategory)
@include('child_category', ['child_category' => $childCategory])
@endforeach
</ul>
@endif
@rakeshjack
Copy link

It was Soo good and helpful. I have a question. How do we get the sub-categories count?
Ex : parent_id = 1,
1->2,
1->3,
2->4,
2->5,
2->6,
5->7,
5->8 ,
6->9,
9->10
Now the parent_id = 2 have child and grand children to count of = 7. How do I get the count.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment