php - Laravel 8 中为 foreach() 提供的参数无效
问题描述
使用 Laravel 8,我有以下带有控制器 index.blade.php 的视图文件
<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<th>#</th>
<th>Title</th>
<th>Body</th>
<th>Created At</th>
<th></th>
</thead>
<tbody>
@foreach ($posts ?? '' as $post)
<tr>
<th>{{$post->id}}</th>
<td>{{$post->title}}</td>
<td>{{ substr($post->body,0,50)}}{{ strlen($post->body) > 50 ? "..." : ""}}</td>
<td>{{ date('M j, Y', strtotime($post->created_at))}}</td>
<td><a href="{{route('posts.show',$post->id)}}" class="btn btn-default btn-sm">View</a><a href="{{route('posts.edit',$post->id)}}" class="btn btn-default btn-sm">Edit</a></td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
和控制器
public function index()
{
$posts = Post::all();
return view('posts.index');
}
但我收到以下错误消息
ErrorException Invalid argument supplied for foreach() (View: F:\2020 technologies\laravel\blog\resources\views\posts\index.blade.php)
这有什么问题。我该如何解决这个问题?
解决方案
您可以使用该方法将数据传递给视图with
。
试试这个:
public function index()
{ $posts = Post::all();
return view('posts.index')->with(compact('posts'));
}
推荐阅读
- java - 我可以使用 KeyListener 更改变量吗?
- python-3.x - 尽管安装了帮助程序,但导入帮助程序库时出错
- javascript - 数组不是函数(评估 'this.props.onPress(e)')
- string - 如何计算 Bash 中字符串中字符的出现次数
- sql - How to INSERT correctly in a VARRAY of TYPE OBJECT?
- blockchain - 如何解决solidity Remix中的类型错误
- amazon-web-services - AWS ASG 生命周期通知目标
- c# - 如何路由 401 和 403 错误?
- c++ - 您将如何嵌套结构?
- xml - XSLT - 未设置根元素