Thanks Michael, i should have thought of that. However, i still have errors. Please find below the complete codes
Category Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'code', 'name','parent_id', 'slug', 'thumbnail',
];
public function children()
{
return $this->hasMany(Category::class, 'parent');
}
public function parent()
{
return $this->belongsTo(Category::class, 'parent');
}
}
Controller Logic
<?php
namespace App\Http\Controllers\Admin;
use App\Category;
use App\Http\Controllers\Controller;
use Cocur\Slugify\Slugify;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$categories = Category::with('children')->whereNull('parent_id')->orderBy('name', 'ASC')->get();
return view('categories')->with('categories', $categories);
}
Blade Template
<div class="row">
@if(!empty($categories))
@foreach($categories as $category)
<div class="col-sm-12 col-lg-6 col-xl-4">
<div class="card card-img-holder">
<div class="card-body list-icons">
<div class="clearfix">
<img src="{{asset('images/categoryThumbnails/'.$category->thumbnail)}}" alt="{{ $category->name }}" title="{{ $category->name }}" width="400" height="255">
<h4>{{ $category->name }}</h4>
</div>
<div class="card-footer p-0">
@foreach($categories->children as $subcategory)
<p class="text-muted mb-0 pt-4">{{ $subcategory->name }}</p>
@endforeach
</div>
</div>
</div>
</div>
@endforeach
@else
<h4>No Categories Added Yet.</h4>
@endif
</div>
Despite all these i still get the
Property [children] does not exist on this collection instance. (View: /Applications/XAMPP/xamppfiles/htdocs/demoProject/resources/views/categories.blade.php)