Home  >  Article  >  Backend Development  >  Laravel 实现获取上一条/下一条记录的功能

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

WBOY
WBOYOriginal
2016-06-20 12:33:211586browse

有时候在文章详情页需要实现显示 上一篇/下一篇 的功能。这个功能非常的常见,现在分享下如何在 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'));}

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

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

source: stackoverflow

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

  • 上一篇: 《 Laravel Eloquent 中 with() 函数只返回指定列》
Statement:
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