Pulling next and previous records with Laravel: Update

Pulling next and previous records with Laravel: Update web View Project

Mar 1, 2014

Previously, I gave a solution for this problem which involved using the use keyword in a PHP closure.

I failed to realize that none of this logic should be in the controller anyway until later. Here is a quick update of my code, which I moved to the Eloquent model. I created two methods; one to pull the previous record, and one to pull the next record.

public function get_next_by_date(){
	return Artwork::select('id', 'title', 'created_at')
		->enabled()
		->where('created_at', '>', $this->created_at) //where the art is newer
		->orWhere(function($query) //or, if the art was made on the same day and the id is greater
		{
			$query->where('created_at', '=', $this->created_at)
				->where('id', '>', $this->id);
		})
		->orderBy('created_at')->orderBy('id') //order by oldest first and smallest id first
		->first(); //get just one record
	}
By using a model's method to grab the next/previous records, it's more clear to the reader and eliminates the need for the use keyword.



Archive
2014