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);
});
})
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);
});
})