Felix
Felix

Reputation: 2661

Laravel next/previous query with conditions and loop arounds

On my site, users can upload images. Images have their own pages.

$user = User::where('username', $username)->first();
$image = Images::where('url_title', $URLtitle)->where('created_by', $user->id)->first();

On these pages, I want a previous/next button that goes to the user's next/previous image. However, I want these to loop around as well.

For example, let's say a user has uploaded 3 images. Images with IDs 33, 55, and 61.

If you were on image 55, the previous image would be 33, and the next image would be 61.

However, if you were on image 61, the next image would loop around to 33.

How could I create a query that would allow me to create these links?

Upvotes: 1

Views: 125

Answers (1)

Thad Blankenship
Thad Blankenship

Reputation: 2302

If you don't mind running some extra queries you could do:

$query = Images::where('url_title', $URLtitle)->where('created_by', $user->id);
$image = $query->first();
$prevImage = $query->where('id', '<', $image->id)->orderBy('id', 'desc')->first();
$nextImage = $query->where('id', '>', $image->id)->orderBy('id', 'asc')->first();

That should give you the nearest images on each side of your selected image.

Upvotes: 1

Related Questions