laravel - 有办法在@foreach 的视图中只显示我的数据库中的最后一项吗?
问题描述
有办法使用@foreach 将我的数据库中添加的最后一项显示到我的家吗?
@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
<div class="fs-rp-item">
<div class="entry-image">
<!--<a href="#"><img src="/holy/images/blog/fs-thumb.jpg" alt="recent post"></a>-->
<a href="#"><img src="/uploads/post/{{$post->id}}/image/{{$post->file_1}}" alt="recent post"></a>
</div>
<div class="entry-rp">
<h4>
<a href="#">{{$post->title}}</a>
</h4>
<p class="read-more">
<a href="#">read the article</a>
</p>
</div>
</div>
@endforeach
解决方案
我不太明白你的问题。对我来说,为了只显示最后一项而迭代循环是没有意义的。
无论如何,这是这样做的方法:
@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
@if($loop->last)
// the end of the loop is reached at this point
@endif
@endforeach
更好的方法是从控制器中的帖子中获取最新项目并将其传递给视图,并仅打印其数据:
use App\Models\Post; // at the top of your class
// your controller
public function index()
{
$post = Post::latest()->first();
return view('index', compact('post'));
}
然后在视图中,您只需使用最新的帖子,例如:
<h4>
<a href="#">{{$post->title}}</a>
</h4>
推荐阅读
- python - 无法读取“https://source.developers.google.com”的用户名
- vba - 如何防止从破坏 HTML 的邮件中删除文本?
- ffmpeg - 迷失在将硬件加速的 ffmpeg 解码器转换为原始环回设备
- python - 如何使用 pandas tz_convert 转换为多个不同的时区
- java - 获取异常-java.lang.IllegalStateException:错误:文本块中不允许drawImage
- owl - owlready2 API 无法访问 https 链接
- sql-server - 如果结果存在则执行存储过程
- html - DOM 中缺少 HTML 分配的“id”
- arrays - 关联来自多个数组的值
- c++ - 节点 FFI 回调。内存泄漏