sortBy('sort', 'asc') and hasNext()

I’m not sure if this is a bug or I might be using it wrong. This snippet is part of an image galley.

$i = $page->images()->sortBy('sort', 'asc')->nth(1);

if($i->hasNext()){
}

The first line of the code is working as expected and giving me the first image sorted by ‘sort’. Actually this image would be the last file when sorted by filename. The problem is that the hasNext() function is returning false in this case what seems not correct in my understanding.

Any suggestions or experiences with this?

The function hasNext() refers to a collection, but your “collection” consists of only one image, so there can’t be a next one.

So depending on what you want to do, you could set this up differently, I guess.

So how could I do this instead? I want is to get a picture by its sorting number and check whether there is a next and a previous image.

For now I solved it like this but this seems not a very elegant solution:

$images = $page->images()->sortBy('sort', 'asc');

$total = $images->count();
$c = 1; 
foreach ($images as $key => $value) {
    if($c == $sortNumber){
        $img = $value; //the image I want to display
        break;
    }
    $c++;
}

if($sortNumber < $total){
    $hasNext = true;
}
else{
    $hasNext = false;
}


if($sortNumber > 1){
    $hasPrev = true;
}
else{
    $hasPrev = false;
}

Thanks for your help.