Skip to content

Instantly share code, notes, and snippets.

@MehulBawadia
Created September 23, 2017 11:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MehulBawadia/58b77fcab85be5018726835e02e0eaa9 to your computer and use it in GitHub Desktop.
Save MehulBawadia/58b77fcab85be5018726835e02e0eaa9 to your computer and use it in GitHub Desktop.
Category with Unlimited Child Categories in Laravel
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Category and Sub Category</title>
</head>
<body>
<div>
<h1>All Categories</h1>
<ul>
@foreach($categories as $category)
<li>{{ $category->name }}</li>
{{-- `isNotEmpty` collection method was added in Laravel 5.3 --}}
@if($category->childs->isNotEmpty())
@include('sub_category_list', [
'childs' => $category->childs
])
@endif
@endforeach
</ul>
</div>
</body>
</html>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'slug', 'parent_id'
];
/**
* A Category has many child categories
*
* @return void
*/
public function childs()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
}
<ul>
@foreach($childs as $parent)
<li>
{{ $parent->name }}
{{-- `isNotEmpty` collection method was added in Laravel 5.3 --}}
@if($parent->childs->isNotEmpty())
@include('sub_category_list', [
'childs' => $parent->childs
])
@endif
</li>
@endforeach
</ul>
<?php
Route::get('/categories', function () {
$categories = \App\Category::whereParentId(0)->get();
return view('welcome', compact('categories'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment