Created
September 23, 2017 11:42
-
-
Save MehulBawadia/58b77fcab85be5018726835e02e0eaa9 to your computer and use it in GitHub Desktop.
Category with Unlimited Child Categories in Laravel
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
<!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> |
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 | |
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'); | |
} | |
} |
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($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> |
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 | |
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