ErrorException 为 foreach() 提供的参数无效 Laravel

ErrorException Invalid argument supplied for foreach() Laravel

我只是想从我的 table 姓名帖子中获取所有数据,但发生错误,它不会让我在我的 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

你最好这样使用with:

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

不在 $posts 中使用单引号

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

或尝试第二种方式

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

你可以使用compact方法

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

您应该将其用作

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

如果其他解决方案无效,请尝试此方法。

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

参见下面的示例:

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


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