This article describes how to obtain data from the previous and next articles in Laravel. For more information, see the origin of the first article and a question about SF:
How can Laravel's Eloquent ORM obtain the next record?
Then, I wrote a simple solution in the answer. However, this acquisition of the next article and the previous record are often encountered in daily Development. the most common scenario may be the acquisition of the previous article and the next article. In fact, this implementation in Laravel's Eloquent is quite easy, but since Laravel does not directly provide us with the corresponding method, we have to use a small trick:
Obtain the id of the previous article
protected function getPrevArticleId($id) { return Article::where('id', '<', $id)->max('id'); }
$ Id is the id of the current article. We use max () to obtain the maximum value smaller than the current id, that is, the id of the previous article of the current id.
Obtain the id of the previous article
protected function getNextArticleId($id) { return Article::where('id', '>', $id)->min('id'); }
It can basically be said that the same can be achieved. This acquisition of the id of the next article is actually an opposite process.
Once we get the id of the previous and next articles, we can do whatever we want, for example:
The code is as follows:
$ Next_article = Article: find ($ this-> getNextArticleId ($ article-> id ));
Say a few more
For the management of an article, we can actually do this:
Add a published_at field to the articles Table. here, you can set the published_at field as a Carbon object. Then, when displaying the front-end, you can determine whether to display the article based on published_at.
For example, the query statement:
public function scopePublished($query) { $query->where('published_at','<=',Carbon::now()); }
// The above method is located in Article, and the following query is stored in ArticleController.
$articles = Article::latest('published_at')->published()...
View display:
@ If ($ prev_article) slug} "rel =" prev ">Previous{{$ Prev_article-> title }}@ endif@ If ($ next_article & $ next_article-> published_at <Carbon \ Carbon: now () slug} "rel =" next ">Next Article{{$ Next_article-> title }}@ endif
The solution for processing the previous and later articles has been completed.
The above is all the content of this article. I hope you will like it.