Skip to content

Instantly share code, notes, and snippets.

@lantrinh1999
Forked from brunocmoraes/Category.php
Created March 17, 2021 06:20
Show Gist options
  • Save lantrinh1999/1a81141f54dcedae597717420a74ecb5 to your computer and use it in GitHub Desktop.
Save lantrinh1999/1a81141f54dcedae597717420a74ecb5 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment