-
-
Save lantrinh1999/1a81141f54dcedae597717420a74ecb5 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