Search code examples
phplaravel-8laravel-collection

Query for the next/previous element in an ordered collection


There exists an Invoice-object that has a id. It correlates to a Bank in a Bank->hasManyThrough(Invoice::class, InvoiceData::class)-relationship.

I now have an arbitrary Invoice-object and want to find the next and the previous one (created_at) that relates to the same Bank.

I wonder if there is an elegant query that can give me the next/previous object without iterating over a collection. Something like:

 $bank->hasManyThrough(Invoice::class, InvoiceData::class)
     ->orderBy('created_at', 'desc')
     ->get($invoice->id)
     ->next();

Solution

  • The query I was searching for was actually this:

    $bank->hasManyThrough(Invoice::class, InvoiceData::class)
        ->latest()
        ->where("id", "<", $invoice->id)
        ->first();
    

    Filtering by everything that has a greater or smaller id prevents that the query gets stuck on objects which are created at the same time.