in my laravel application I have categories and subcategories in the same db table. Any Category with NULL in parent column is a parent category while any category with an ID in its parent column is a subcategory.
In my view table I want to have the number of subcategories beside each parent category but I don't know how to pass the number of each subcategory along with the parent category from the control to view
public function index()
{
//select parent categories
$arr['categories'] = Category::where('parent', NULL)->orderBy('category', 'asc')->get();
return view("admin.categories")->with($arr);
}
@foreach($categories as $item)
<td>{{$count }}</td>
<td>{{$item->category}}</td>
<td>#</td>
<td>@if($item->id != 0)
<a href="categories/{{$item->id}}/edit"><img src="{{asset('assets/images/edit.png')}}" alt="Update" title="Update" width="20" align="left" style="margin-right:20px;"></a>
<form action="{{ url('admin/categories' , $item->id ) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<input type="image" src="{{asset('assets/images/delete.png')}}" alt="Delete" title="Delete" width="20" onClick="return deleteItem();">
@endif</td>
@endforeach
CodePudding user response:
App\Models\Category.php
public function subcategory()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
App\Http\Controllers\CategoryController.php
public function index()
{
//select parent categories
$arr['categories'] = Category::withCount('subcategory')->where('parent', NULL)->orderBy('category', 'asc')->get();
return view("admin.categories")->with($arr);
}
resources\views\admin\categories.blade.php
@foreach($categories as $item)
...
<td>{{ $item->subcategory_count }}</td>
...
@endforeach
CodePudding user response:
Issue rectified. I just added in to my Category Model
public function subCategories()
{
return $this->hasMany(static::class, 'parent');
}
and added this to my view
{{@count($item->subCategories)}}
@foreach($item->subCategories as $subCaty)
{{$subCaty->category}},
@endforeach
that did the magic
I got the help from youtube.com/watch?v=1N8KoF4H218