Laravel 实现获取上一条/下一条记录的功能

WBOY
Release: 2016-06-20 12:33:21
Original
1628 people have browsed it

有时候在文章详情页需要实现显示 上一篇/下一篇 的功能。这个功能非常的常见,现在分享下如何在 Laravel 中实现这样的功能。

首先需要在 Controller中显示文章的方法(如: show())中查询出上一条/下一条记录:

public function show($id){    // get the current post    $post = Post::find($id);    // get previous post id    $previous = Post::where('id', '<', $post->id)->max('id');    // get next post id    $next = Post::where('id', '>', $post->id)->min('id');    return view('posts.show', compact('previous', 'next'));}
Copy after login

接着就可以在视图中添加上一篇/下一篇的链接了:

<a href="{{ URL::to( 'posts/' . $previous ) }}">Previous</a><a href="{{ URL::to( 'posts/' . $next ) }}">Next</a>
Copy after login

source: stackoverflow

该篇属于专题:《Laravel小技巧》

  • 上一篇: 《 Laravel Eloquent 中 with() 函数只返回指定列》
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!