亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在一個頁面上顯示所有用戶的帖子

如何在一個頁面上顯示所有用戶的帖子

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 關注
  • 172 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號