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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44715346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:11:48  来源:igfitidea点击:

ErrorException Invalid argument supplied for foreach() Laravel

laravelforeachblade

提问by Lestah

I'm just trying to get all the data from my table name posts but an error occur it wont let me display the data on my index.blade.php

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

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

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

    }

and here's my index.blade.php

这是我的 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

采纳答案by Ramzan Mahmood

You should use it as

你应该把它用作

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

回答by Amarnasan

You'd better use withlike this:

你最好这样使用with

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

回答by gecko

If the other solutions were not working, try this.

如果其他解决方案不起作用,请尝试此操作。

I may think that you just missed this single line "enctype="multipart/form-data"in your form.

See example below:

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

请参见下面的示例:

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


Don't forget to click the arrow up. I hope I did help you :)


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

回答by Vishal Varshney

not use single quote in $posts

不要在 $posts 中使用单引号

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

or try second way as

或尝试第二种方式

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

回答by Dharmesh Rakholia

You can use compactmethod

你可以使用compact方法

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