如何在一个页面上显示所有用户的帖子

这是我在用户个人资料页面中使用的代码,效果很好


@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

现在我想在主页上显示所有用户的帖子


怎么做 ?


翻翻过去那场雪
浏览 104回答 3
3回答

慕标5832272

如果你Post在控制器中有一个模型,你可以这样。public function index(){&nbsp; &nbsp;$posts = Post::all();&nbsp; &nbsp;return view('home')->with('posts', posts);}<ul>@foreach($posts as $post)&nbsp; <li>&nbsp; &nbsp; &nbsp;<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100 h-100">&nbsp; </li>@endforeach</ul>希望对你有帮助。

慕的地8271018

只需在控制器中调用 post 模型即可$posts = Post::select('columns_name')->get();压缩变量,你可以像这样使用@forelse($posts as $post)&nbsp; &nbsp; &nbsp; {{$post->id}}@empty&nbsp; &nbsp;No post found@endforelse

12345678_0001

如果您在 Post 模型中有这样的关系:public function users()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this -> belongsToMany(User::class, 'user_posts');&nbsp; &nbsp; }//'user_posts' 是你的带有外键的数据库表在控制器中使用:$posts=Post::with('users')->get();然后在视图中:@foreach ($posts as $post)&nbsp; &nbsp; <div class="col-4 mb-4">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href="{{ route('posts.show', ['post' => $post->id]) }}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="{{ asset('storage') . '/' . $post->image }}" class="w-100 h-100">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href="{{ route('users.show', ['user' => $post-> user -> id]) }}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{ $post-> user -> name }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</a>&nbsp; &nbsp; </div>@endforeach
打开App,查看更多内容
随时随地看视频慕课网APP