JasperK's avatar

Custom order of Eloquent, get next/prev article?

Hi, How do I get a previous / next article when there is a custom order?

# I'm ordering my Articles by publish_date in the overview
$articles = Article::orderBy("publish_date")->get();
# I find articles by their Slug
$article = Article::whereSlug("foobar")->first();

# I'm ordering my Projects by Title in the overview
$projects = Project::orderBy("title")->get();
# I find articles by their Slug
$project = Project::whereSlug("other")->first();

How can I find the next() and prev() article, based on the previous ordering?

Can I use the pagination in some way for this?

0 likes
1 reply
bestmomo's avatar

Something like that :

$next = Article::orderBy("publish_date")->where('publish_date', '>', $article->publish_date)->first();
$previous = Article::orderBy("publish_date", 'desc')->where('publish_date', '<', $article->publish_date)->first();
1 like

Please or to participate in this conversation.