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.

Revisions

  1. @brunocmoraes brunocmoraes created this gist Aug 9, 2020.
    15 changes: 15 additions & 0 deletions Category.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    <?php
    class Category extends Model
    {

    public function categories()
    {
    return $this->hasMany(Category::class);
    }

    public function childrenCategories()
    {
    return $this->hasMany(Category::class)->with('categories');
    }

    }
    10 changes: 10 additions & 0 deletions caregories.blade.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    <ul>
    @foreach ($categories as $category)
    <li>{{ $category->name }}</li>
    <ul>
    @foreach ($category->childrenCategories as $childCategory)
    @include('subcategories', ['child_category' => $childCategory])
    @endforeach
    </ul>
    @endforeach
    </ul>
    7 changes: 7 additions & 0 deletions create_categories_table.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    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();
    });
    8 changes: 8 additions & 0 deletions subcategories.blade.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    <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