Felix Maxime Felix Maxime - 3 years ago 154
MySQL Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download