Bump
Pagination Help/Logic
Hello all,
I'm unsure of how to tackle pagination for a bunch of photos at the following routes:
/photos
/photos/popular
/profiles/{slug}/photos
Lets say from /photos, I click the first photo. On this page /photos/1 I navigate to the next photo which is now /photos/2. This is fine.
But if I now navigate to /photos/popular and click the first photo, which is potentially /photos/1709 and I click next - my existing code will simply take me to the next photo based in it's id. So potentially /photos/1710.
The same applies for the /profiles/{slug}/photos route, I want to take into account the way a user hits a photo page.
So here's my existing code for fetching the next and previous photos;
/**
* The previous photo.
*
* @param integer $id
* @return mixed
*/
public static function previous($id)
{
return static::where('id', '<', $id)->first();
}
/**
* The next photo.
*
* @param integer $id
* @return mixed
*/
public static function next($id)
{
return static::where('id', '>', $id)->first();
}
(Used on my Photo model, Photo::next($id) returns the next photo.)
How would you recommend I amend my existing code above? Sorry if anythings not clear!
Thanks in advance :)
@JoeDawson I think I understand what you're saying now. If they clicked on a photo while on the popular page, why don't you send them to a different route like photos/popular/123? Dribble does something similar. From there, you can specifically query based on popularity and do something similar to what you did before. You just need to use the having() method. Obviously, you would need to refactor this and you can probably clean it up, but here's quick fix based on your query.
// Get photo based on the id passed in URL
$mainPhoto = Photo::leftJoin('views','photos.id','=','views.photo_id')->
selectRaw('photos.*, count(views.photo_id) AS `count`')->
groupBy('photos.id')->
orderBy('count','DESC')->
where('photos.id', '=', $id)->
first();
// nextPhoto is the first photo with less views than the mainPhoto
$nextPhoto = Photo::leftJoin('views','photos.id','=','views.photo_id')->
selectRaw('photos.*, count(views.photo_id) AS `count`')->
groupBy('photos.id')->
orderBy('count','DESC')->
having('count', '<', $mainPhoto->count)->
first();
// prevPhoto is the first photo with more views than the mainPhoto
$prevPhoto = Photo::leftJoin('views','photos.id','=','views.photo_id')->
selectRaw('photos.*, count(views.photo_id) AS `count`')->
groupBy('photos.id')->
orderBy('count','DESC')->
having('count', '>', $mainPhoto->count)->
first();
Another option is to save the list of photos from your pagination query (18 photos based on your query). You save and paginate through that list. Once you reach the end of that list, you query the pagination for the next page and cycle through that.
Please or to participate in this conversation.