First the origin of the article comes with a question above SF:
Laravel eloquent ORM How to get the next line of the current record
Then, in the answer, I wrote a simple solution. However, since this acquisition of the next and get the previous record in the daily development is still often encountered, the most common scenario may be to get an article on the last article and the next article. In fact, this in the laravel eloquent implementation is quite easy, but because Laravel does not directly provide us with the appropriate method, we have to use a small trick:
Get the article ID of the previous article
protected function Getprevarticleid ($id)
{return
article::where (' id ', ' < ', $id)->max (' id ');
}
$ID is the ID of the current article, and we get Max () with the maximum value that is smaller than the current ID, which is the ID of the previous post for the current ID.
Get the article ID of the previous article
protected function Getnextarticleid ($id)
{return
article::where (' id ', ' > ', $id)->min (' id ');
}
Basically, it can be said that the same can be done. This gets the ID of the next article is actually a reverse process, understand long live.
Once we've got the last and next article IDs, we can do whatever we want, like:
Copy Code code as follows:
$next _article = Article::find ($this->getnextarticleid ($article->id));
Two more words.
So if it's for the management of an article, we can actually do this:
Add a published_at field to the articles table where you can set the Published_at field to a carbon object, and then we can interpret the article by Published_at when we show it on the front.
For example, query statements:
Public Function scopepublished ($query)
{
$query->where (' published_at ', ' <= ', Carbon::now ());
}
The above method is located in article, the following query I put in the Articlecontroller
$articles = article::latest (' published_at ')->published () ...
View Show:
<li class= "Previous" >
@if ($prev _article) <a href= "
/post/{{$prev _article->slug}}" rel= "prev" ><i class= "FA fa-chevron-left" ></i><strong> previous </strong><span> {{$prev _article- >title}}</span> </a>
@endif
</li>
<li class= "Next" >
@if ($next _article && $next _article->published_at < Carbon\carbon::now ())
<a href= "/post/{{$next _article-> Slug}} "rel=" Next "><i class=" fa fa-chevron-right "></i><strong> next </strong> <span> {{$next _article->title}}</span></a>
@endif
</li>
The solution that handles the previous and the last article is complete.
The above mentioned is the entire content of this article, I hope you can enjoy.