DEV Community


Posted on • Originally published at on

Getting previous and next record in Laravel

This post was originally published at PostSrc 🔥🔥🔥. If you like this kind of tutorial, I would really appreciate it if you give it a visit.

Getting previous and next record in Laravel

To be able to navigate around through the previous and next resources is a very handy feature to have. This will enable easy navigation between the record on both sides (left and right). The implementation is quite straight forward but certain logic has to be clearly defined to get the right result in the model.

Example Scenario

  • PostSrc previous and next post
  • Laracast previous and next episode series

There are several ways to implement this functionality and the simplest way is to use the Model Id. Since by right an Id auto increment, we can assume that the newest post will always have a higher number than the oldest post.

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('', compact('post', 'previous', 'next'));
Enter fullscreen mode Exit fullscreen mode

In the example above we are getting the default post by querying using the "id". To get the previous and next post we make use of the where clause by getting the lowest and highest post model "id" value. Once we get the models, we are comparing them with the other models we are getting the "max" for the previous post and "min" for the next post and this essentially filters the model to get only one that matches the criteria.

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('', compact('episode', 'previous', 'next'));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)