Created
August 9, 2020 20:14
-
-
Save brunocmoraes/160567d00f944f9f083a324101d5c002 to your computer and use it in GitHub Desktop.
Eloquent: Recursive hasMany Relationship with Unlimited Subcategories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ul> | |
@foreach ($categories as $category) | |
<li>{{ $category->name }}</li> | |
<ul> | |
@foreach ($category->childrenCategories as $childCategory) | |
@include('subcategories', ['child_category' => $childCategory]) | |
@endforeach | |
</ul> | |
@endforeach | |
</ul> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Category extends Model | |
{ | |
public function categories() | |
{ | |
return $this->hasMany(Category::class); | |
} | |
public function childrenCategories() | |
{ | |
return $this->hasMany(Category::class)->with('categories'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.