为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
翻翻过去那场雪 2023-03-04 14:26:55
这是我在用户个人资料页面中使用的代码,效果很好@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现在我想在主页上显示所有用户的帖子怎么做 ?
查看完整描述

3 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

如果你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>

希望对你有帮助。


查看完整回答
反对 回复 2023-03-04
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

只需在控制器中调用 post 模型即可


$posts = Post::select('columns_name')->get();

压缩变量,你可以像这样使用


@forelse($posts as $post)

      {{$post->id}}

@empty

   No post found

@endforelse


查看完整回答
反对 回复 2023-03-04
?
12345678_0001

TA贡献1802条经验 获得超5个赞

如果您在 Post 模型中有这样的关系:


public function users()

    {


        return $this -> belongsToMany(User::class, 'user_posts');

    }

//'user_posts' 是你的带有外键的数据库表


在控制器中使用:


$posts=Post::with('users')->get();

然后在视图中:


@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


查看完整回答
反对 回复 2023-03-04
  • 3 回答
  • 0 关注
  • 101 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信