简体   繁体   English

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

[英]Undefined Variable 'Comments' in Compact Laravel

I am getting 'undefined offset 1' error.我收到“未定义偏移量 1”错误。 It does returns everything I need -> the posts and the comments in the category.它确实返回了我需要的所有内容 -> 类别中的帖子和评论。 However, I believe the 'Undefined Offset 1' problem is probably due to some post which have no replies to them??但是,我认为“未定义偏移 1”问题可能是由于某些帖子没有回复他们?? -> thus, help. -> 因此,帮助。

I have 1. Category Model 2. Post Model 3. Comment Model我有 1. 分类模型 2. 发布模型 3. 评论模型

This is the show function in my Category Model这是我的类别模型中的显示功能

  public function show($id)
    {

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


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

I have made relation for 'Category hasMany Posts' -> 'Post hasMany Comments'.我已经为“类别有许多帖子”->“发布有许多评论”建立了关系。

You can try this你可以试试这个

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'));
}

Alternative method替代方法

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
    */
}

You are creating $comments variable inside foreach loop that make it's scope locally and will not be available outside foreach您正在foreach循环内创建$comments变量,使其成为本地范围,并且在foreach之外不可用

To resolved this error you need to define your comments variable inside your function so that it is available in your function要解决此错误,您需要在您的函数中定义您的comments变量,以便它在您的函数中可用

public function show($id)
        {
            $comments = [];  // define it here
            $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'));
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM