Get the next and previous post

  1. 3 years ago

    Hi there,

    how would I go about getting the next and previous post having in mind that I'm on the post detail page.

    I know the logic would be to pick the current post id from here:

    $post = $this->posts->findBySlug($slug);

    and then get the next and previous one using something like:

    $next = DB::table('posts')->where('id', '>', $post->id)->get();
    $previous = DB::table('posts')->where('id', '<', $post->id)->get();

    but somehow this is not working. :-(

  2. Solved, I should've been using first() and not get. And I should obviously use a order by statement too.

  3. Edited 3 years ago by marcogmonteiro

    In case someone needs this:


    	public function getShow($slug)
    		$post = $this->posts->findBySlug($slug);
    		$prev = DB::table('posts')->orderBy('id', 'asc')->where('id', '>', $post->id)->where('active', '1')->first();
    		$next = DB::table('posts')->orderBy('id', 'desc')->where('id', '<', $post->id)->where('active', '1')->first();
    		if ( ! $post)
    			return App::abort(404, 'Page not found');
    		return View::make('themes.'.$this->theme.'.post', compact('post', 'next', 'prev'));

    and you can see this result here:

or Sign Up to reply!