Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

242Studios's avatar

Query last element in where clause?

Good day, I want to write an eloquent query that filters a package by the checkpoint it's at, however at the moment it is matching to all packages that have the checkpoint in its relationship, for example, a package could have checkpoint A, B or C in its pivot table, given that A and B could have been past checkpoints. i only need to match the last/latest checkpoint (C) to the filter. How would I do this? Below is my current code showing this section.

->when($checkpoint, function ($query) use ($checkpoint) {
        return $query->whereHas('packages.checkpoints', function ($query) use ($checkpoint) {
          return $query->where('checkpoint_id', $checkpoint);
        });
      })
0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You can use the approach of making a relationship for the latest Checkpoint, and using that instead:

//Package model
public function latestCheckpoint()
{
    return $this->hasOne(Checkpoint::class)->latestOfMany();
}
->when($checkpoint, function ($query) use ($checkpoint) {
    return $query->whereHas('packages.latestCheckpoint', function ($query) use ($checkpoint) {
        return $query->where('checkpoint_id', $checkpoint);
    });
})

Please or to participate in this conversation.