簡體   English   中英

緊湊型 Laravel 中未定義的變量“注釋”

[英]Undefined Variable 'Comments' in Compact Laravel

我收到“未定義偏移量 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
    */
}

您正在foreach循環內創建$comments變量,使其成為本地范圍,並且在foreach之外不可用

要解決此錯誤,您需要在您的函數中定義您的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