origin
First of all, the origin of the article comes from a question:
How to get the next item of the current record in Laravel's Eloquent ORM
I want to get the next item and change its active field to yes, but it seems that it cannot be obtained
$next_active = $ips->where("id", ">", $ips_get->id)->first(); $next_active->update(["active" => "yes"]);
Then, I briefly wrote a solution in the answer. However, since the record of obtaining the next and obtaining the previous one is still often encountered in daily development, the most common scenario may be to obtain the previous and next articles of an article. Actually, this isLaravel
ofEloquent
It's quite easy to implement, but becauseLaravel
There is no corresponding method provided directly to us, we have to use a small trick:
Get the previous article id
protected function getPrevArticleId($id) { return Article::where('id', '<', $id)->max('id'); }
$id is the current articleid
, we passmax()
To get the current oneid
The small maximum value is the current valueid
The previous articleid
。
Get the next article id
protected function getNextArticleId($id) { return Article::where('id', '>', $id)->min('id'); }
Basically, it can be said:The same is true
. This gets the next articleid
In fact, it is a reverse process, long live understanding.
Once we get the ids of the previous and next articles, we can do whatever we want, for example:
$next_article = Article::find($this->getNextArticleId($article->id));
Say a few more words
If it is for the management of an article, we can actually do this:
Givearticles
Add one to the tablepublished_at
The fields ofpublished_at
Set the field to aCarbon
We can then display the object in the front-end according topublished_at
Let's judge whether to display the article.
For example, query statement:
public function scopePublished($query) { $query->where('published_at','<=',Carbon::now()); } //The above method is located in Article, I put the following query in ArticleController$articles = Article::latest('published_at')->published()...
View display
<li class="previous"> @if($prev_article) <a href="/post/{{ $prev_article->slug }}" rel="external nofollow" rel="prev"><i class="fa fa-chevron-left"></i><strong>Previous article</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="external nofollow" rel="next"><i class="fa fa-chevron-right"></i><strong>Next article</strong> <span> {{ $next_article->title }}</span></a> @endif </li>
The solution to deal with the previous and next articles of the article has been completed.
The above is the detailed explanation of the implementation of the id of Laravel Eloquent to retrieve the previous and next data. For more information about the id of Laravel Eloquent to retrieve the data, please pay attention to my other related articles!