Example Scenario
- PostSrc previous and next post
- Laracast previous and next episode series
Previous and Next Implementation
To get the previous and next posts we'll be using the code below. Do note that it's within the controller that you have defined in, otherwise any other places suitable in your application.
function show(int $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('post', 'previous', 'next')); }
Previous and Next Video / Episode
In other case scenarios where you are not making use of the model "id", you need to define a column such as "episode_number" where it will store the numeric value.
function show(int $id) { // get the current episode $episode = Episode::find($id); // get previous episode number $previous = Episode::where('episode_number', '<', $post->episode_number)->max('episode_number'); // get next episode number $next = Episode::where('episode_number', '>', $post->episode_number)->min('episode_number'); return view('episodes.show', compact('episode', 'previous', 'next')); }