[英]How to display the posts of all users on one page
Here is the code I used in a user's profile page and it works fine这是我在用户个人资料页面中使用的代码,它工作正常
@foreach ($user->posts as $post)
<div class="col-4 mb-4">
<a href="{{ route('posts.show', ['post' => $post->id]) }}">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100 h-100">
</a>
</div>
@endforeach
Now I would like to display the posts of all users on the home page现在我想在主页上显示所有用户的帖子
How to do?怎么做?
If you have a Post
model in the controller you could something like this.如果你在 controller 中有一个
Post
后,你可以这样。
public function index()
{
$posts = Post::all();
return view('home')->with('posts', posts);
}
<ul>
@foreach($posts as $post)
<li>
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100 h-100">
</li>
@endforeach
</ul>
Hope it helps you.希望它可以帮助你。
Just call the post model in your controller like只需在 controller 中调用 model 后即可
$posts = Post::select('columns_name')->get();
compact the variable and you can use like压缩变量,你可以使用
@forelse($posts as $post)
{{$post->id}}
@empty
No post found
@endforelse
If you have the relation in Post model like:如果您在 model 后有这样的关系:
public function users()
{
return $this -> belongsToMany(User::class, 'user_posts');
}
//where 'user_posts' is your db table with foreign keys //其中'user_posts'是您的带有外键的数据库表
In Controller use:在 Controller 中使用:
$posts=Post::with('users')->get();
Then in view:然后在视图中:
@foreach ($posts as $post)
<div class="col-4 mb-4">
<a href="{{ route('posts.show', ['post' => $post->id]) }}">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100 h-100">
</a>
<a href="{{ route('users.show', ['user' => $post-> user -> id]) }}">
{{ $post-> user -> name }}
</a>
</div>
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.