Reputation: 89
I'm trying to get the next and previous items (title and image) for each topic and I have this for next and previous links:
$currentUser = PostTranslation::find($post->id);
$previousUserID = PostTranslation::where('id', '<', $currentUser->id)->max('id');
$nextUserID = PostTranslation::where('id', '>', $currentUser->id)->min('id');
but it's just get the next and previous link id, which I need to get the title for them too. I have used this:
$previousUserID2 = PostTranslation::find($currentUser->id-1);
but it's when id = 0
that I am getting an error.
Upvotes: 1
Views: 2993
Reputation: 89
That's last code i have been used at my controller :
$previousUser = PostTranslation::join('posts', 'posts.id', '=', 'post_translations.post_id')
->where('posts.id', '<', $currentUser->id)
->select('posts.id','post_translations.title','post_image')
->orderby('posts.id','desc')
->where('post_translations.language', $language)
->first();
Upvotes: 0
Reputation: 15464
If your dataset is too big max and min can slow down your sql.
You can use first
along with orderby
which retrieve the first model matching the query constraints.
$currentUser = PostTranslation::find($post->id);
//order by descending order and take the first entry
$previousUser = PostTranslation::where('id', '<', $currentUser->id)->select('id','title')->orderby('id','desc')->first();
$previous_id=$previousUser ->id;
$previous_title=$previousUser ->title;
//order by ascending order and take the first entry
$nextUser = PostTranslation::where('id', '>', $currentUser->id)->select('id','title')->orderby('id','asc')->first();
$next_id=$nextUser ->id;
$next_title=$nextUser ->title;
Upvotes: 3