[英]How to display the posts of all users on one page
這是我在用戶個人資料頁面中使用的代碼,它工作正常
@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
現在我想在主頁上顯示所有用戶的帖子
怎么做?
如果你在 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>
希望它可以幫助你。
只需在 controller 中調用 model 后即可
$posts = Post::select('columns_name')->get();
壓縮變量,你可以使用
@forelse($posts as $post)
{{$post->id}}
@empty
No post found
@endforelse
如果您在 model 后有這樣的關系:
public function users()
{
return $this -> belongsToMany(User::class, 'user_posts');
}
//其中'user_posts'是您的帶有外鍵的數據庫表
在 Controller 中使用:
$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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.