Learn to code with Laravel | Laravel Resource Centre

How to find the Next or Previous item in the database. Laravel

There are many circumstances in which you will want to find the next or previous item to the current item in the database. A good use case for this is when building a video player and you need to find out the next video to play or the previous video.

As always, there are a thousand ways to achieve this result, but I am going to stick with the simplest of the various methods. This is not genuinely my idea, I found this solution of StackOverflow and I thought it will be great to share it with you.

One thing to keep in mind is to never load an entire table then loop through it, just to find the next or previous item as this will certainly affect performance. You may not notice the difference on a small application.

The solution to How to find the Next or Previous item in the database. Laravel

Already we have a reference to the current item


Now we need to find the next item

$next = App\Video::orderyBy('id')->where('id', '>', $currentItem->id)->first();

I suppose now you can figure it out on how to find the previous item, simply replace the > with a <

$next = App\Video::orderyBy('id')->where('id', '>', $currentItem->id)->first();

What the above code does

We are getting the first item from a collection that is ordered according to the id.

Support us Grow

If you find this post helpful please leave a comment below and if it is rather confusing or unclear, please drop a comment below and I will do my best to rework it.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button