laravel8 : 此集合实例上不存在

问题描述

我想在导航栏中显示我的所有类别并在下拉列表中显示它们的子类别 像这样:

enter image description here

我有一个 home.blade.PHP 并在其中扩展了导航刀片,还有一个 HomeController。

问题是我可以显示类别和子类别,但不能显示标题

当我将 foreach 用于 nav 时,{{$category->children}} 工作并显示所有孩子,但是当我使用它时 {{$category->children->title}} 它不起作用并说:

Property [title] does not exist on this collection instance

另外,category 和 subcategory 的关系如下:

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
         'parent_id','title','description','status',];

    public function parent()
    {
    return $this->belongsTo(Category::class);
    }


    public function children(){
        return $this->hasMany(Category::class,'parent_id');
    }
}

所以这是我的 HomeController :

 public function index()
    {
        $categories = Category::with('children')
        ->whereNull('parent_id')
        ->get();

        return view('home.home',compact('categories'));
    }

还有我的导航刀片:

 @foreach($categories as $category)
    <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"> {{ $category->title }} <span class="caret"></span></a>
        <ul class="dropdown-menu" >
          <li><a href="#">{{ $category->children->title }}</a></li>

        </ul>
      </li>
    @endforeach

正如我上面提到的,我只是扩展了主页刀片中的导航

你能告诉我我哪里错了吗?

解决方法

您需要为孩子们​​执行另一个 foreach 循环来解析它们。

将您的导航刀片更改为:

@foreach($categories as $category)
    <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"> {{ $category->title }} <span class="caret"></span></a>
        <ul class="dropdown-menu" >
          @foreach($category->children as $child)
             <li><a href="#">{{ $child->title }}</a></li>
          @endforeach
        </ul>
      </li>
@endforeach