duddy67's avatar

Getting the last element in a collection ?

Hi, I need to get the last element in my payments collection.

$payment = $this->payments->last();

But it doesn't return the last element of the collection. On the other hand the first() method does:

$payment = $this->payments->first(); 

So what is last() for and how to use it ?

0 likes
8 replies
Snapey's avatar

You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:

collect([1, 2, 3, 4])->last();
 
// 4

If it did not do this then it would be a bug and have been fixed years ago

jaseofspades88's avatar

I assume you're not ordering your payments correctly on your relationship or however you're placing them into a collection. Presumably you've ordered them ascending instead of descending and would explain why 'first' is the 'last'.

Explicitly order and then take the last, using something like ->latest() on your query builder. Other than that, we're just guessing at why your payments are incorrectly ordered.

duddy67's avatar

@snapey It doesn't do this. I have currently 2 rows in my payments table, and last() returns the first one. Any idea ?

Snapey's avatar

@duddy67 Now you are talking about a table. Which is it? A collection or a database query?

duddy67's avatar

@snapey It's a collection. $payment = $this->payments->last(); I just mentioned the table to point out that I'm not getting the last element.

shariff's avatar

If your using table then you need to use latest. Try getting like this $payment = $this->payments->lastest()->first();

Snapey's avatar

dd($this->payments) and post the result?

duddy67's avatar

My bad. I totally forgot about the orderBy clause in my Model.

public function payments(): MorphMany
{
  return $this->morphMany(Payment::class, 'payable')->orderBy('created_at', 'desc');
}

It was the reason why the last() method worked the other way around.

Please or to participate in this conversation.