【发布时间】:2019-10-05 23:42:56
【问题描述】:
我有两个表,用户和帖子表在 Laravel 5.5 中使用一对多关系链接在一起。我只想显示与登录用户相关的帖子。
我有 PostController,我在其中获取当前用户登录并将其传递给视图 index.php。在 index.php 视图中,我尝试使用@foreach 获取和循环与登录用户关联的帖子。
请参阅下面的示例代码。
后控制器
public function index()
{
$currentuser = Auth::user();
return view('posts.index')->withCurrentuser($currentuser);
}
index.php 视图
@foreach ($currentuser->posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ substr(strip_tags($post->body), 0, 40) }}{{ strlen(strip_tags($post->body))>40 ? "..." : "" }}</td>
<td>{{ date('M j, Y', strtotime($post->created_at)) }}</td>
<td><a href="{{ route('posts.show', $post->id) }}" class="btn btn-outline-blue btn-sm">View</a> <a href="{{ route('posts.edit', $post->id)}}" class="btn btn-sm btn-outline-blue">Edit</a></td>
</tr>
@endforeach
User.php 模型
protected $table = 'users';
public function post(){
return $this->hasMany('App\Post');
}
Post.php 模型
public function users(){
return $this->belongsTo('App\User');
}
我收到一个错误
为 foreach() 提供的参数无效
问题可能出在哪里?
【问题讨论】:
标签: php laravel-5.5