Laravel - How to get next or previous post data
Categories - Laravel PHP Framework Tags - Laravel   Maniruzzaman Akash   4 years ago   2639   1 minute   1

Laravel - How to get next or previous post data

In this article, we'll learn how to get the next and previous post data for a post or an article modal or any types of modal.

  /**
   * getNextOrPreviousPost
   *
   * @param integer $post_id Post/Article/Modal ID
   * @param string $type Type of post, next/previous
   * @return object The previous or next post according to any post
   */
  public static function getNextOrPreviousPost($post_id, $type = "next")
  {

    $post = new Post();
    if ($type == "next") {
      $post = $post->where('id', '>', $post_id);
    } else {
      $post = $post->where('id', '<', $post_id);
    }
    $post = $post->limit(1)->first();
    return $post;
  }

 

Or, If we want to make it in Laravel DB Query Builder:

public static function getNextOrPreviousPost($post_id, $type = "next")
{
  if ($type == "next") {
    $post = DB::table('posts')->where('id', '>', $post_id);
  } else {
    $post = DB::table('posts')->where('id', '<', $post_id);
  }
  $post = $post->limit(1)->first();
  return $post;
}

 

Details:

params 1:

In first parameter, we've get the post_id or model's primary_id. 

params 2:

In second parameter, we've passed the type of getting data

return:

returns the object of the required post/model's data

 

 Logic Bihind How to get next or previous post data:

  1. First check the type
  2. If type is next, get the greater than post of this post
  3. If type is previous, get the less than post of this post
  4. Then fetch as limit 1 and get the first data

 

Previous
PHP If-else-elseif and Switch-case
Next
PHP String Functions - All necessary String functions in PHP to manage strings better.