紧凑型 Laravel 中未定义的变量“注释”

JasonPython初学者

我收到“未定义偏移量 1”错误。它确实返回了我需要的所有内容 -> 类别中的帖子和评论。但是,我认为“未定义偏移 1”问题可能是由于某些帖子没有回复他们??-> 因此,帮助。

我有 1. 分类模型 2. 发布模型 3. 评论模型

这是我的类别模型中的显示功能

  public function show($id)
    {

        $category = Category::with('posts.comments')->find($id);


        return view('categories.show', compact('category'));
    }

我已经为“类别有许多帖子”->“发布有许多评论”建立了关系。

泰勒香农

你可以试试这个

public function show($id)
{
    $comments = []; // Empty array to initialize the variable. This variable will be filled once the foreach statement is ran.
    $category = Category::find($id);
    if($category !== null) {
        $posts = $category->posts;

        foreach($posts as $post) {

            $comments = $post->comments;
        }

    }
    return view('categories.show', compact('posts', 'category', 'comments'));
}

替代方法

public function show(Category $category) //same as... public function show($id)
{
    return view('categories.show', compact('category'));
    /*
    Render this content in the view.
    @foreach($category->posts as $post)
      {{-- Display Post Content --}}
      @foreach($post->comments as $comment)
        {{-- Display Comment Content --}}
      @endforeach
    @endforeach
    */
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章