【问题标题】:ErrorException Invalid argument supplied for foreach() LaravelErrorException 为 foreach() Laravel 提供的参数无效
【发布时间】:2017-11-26 16:11:12
【问题描述】:

我只是想从我的表名帖子中获取所有数据,但发生错误,它不会让我在 index.blade.php 上显示数据

public function index()
    {
        //
        $posts = Post::all();

        return view('posts.index')->withPosts('$posts');

    }

这是我的 index.blade.php

@foreach( $posts as $post )
            <div class="post-preview">
                    <a href="post.html">
                        <h2 class="post-title">

                            {{ $post->title }} -> this is the one i want to display

                        </h2>
                        <h3 class="post-subtitle">

                            {{ $post->body }}

                        </h3>
                    </a>
                    <p class="post-meta">Posted by <a href="#">Start Bootstrap</a> on September 24, 2014</p>
                    <button type="button" class="btn btn-secondary">&nbsp;&nbsp;Edit&nbsp;&nbsp;&nbsp;</button>
                    <button type="button" class="btn btn-secondary">Delete</button>
            </div>

                <hr>
            @endforeach

【问题讨论】:

  • dd($posts) 在你的控制器中看看有什么输出?
  • 并尝试以return view('posts.index')-&gt;with(compact('posts'));返回
  • @blue moon 嘿,您的代码有效,感谢您的帮助
  • @blue moon 怎么办?

标签: laravel foreach blade


【解决方案1】:

你应该把它当作

return view('posts.index')->with(compact('posts'));

【讨论】:

    【解决方案2】:

    你最好像这样使用with

    return view('posts.index')->with('posts',$posts);
    

    【讨论】:

      【解决方案3】:

      不要在 $posts 中使用单引号

      return view('posts.index')->withPosts($posts);
      

      或尝试第二种方式

      return view('posts.index', compact('posts'));
      

      【讨论】:

        【解决方案4】:

        你可以使用compact方法

        return view('posts.index',compact('posts'));
        

        【讨论】:

          【解决方案5】:

          如果其他解决方案不起作用,试试这个。

          我可能认为您只是错过了表单中的这一行 "enctype="multipart/form-data"

          见下面的例子:

          <form action="{{ route('upload.files') }}" method="POST" enctype="multipart/form-data">
          <input id="fileupload" type="file" name="attachment[]" multiple>
          </form>
          


          不要忘记单击向上箭头。希望对你有所帮助:)

          【讨论】:

            猜你喜欢
            • 2019-11-11
            • 1970-01-01
            • 2018-12-09
            • 1970-01-01
            • 2015-06-29
            • 2022-01-27
            • 2018-02-26
            • 2021-12-25
            • 2019-10-05
            相关资源
            最近更新 更多