Collection::last

Returns the last item in the collection, or the last item passing a given truth test.

Signature
public function last(?callable $callback = null, mixed $default = null): mixed

Parameters

ParameterTypeDescription
$$callbackoptionalcallable|null= nullTruth test receiving ($value, $key); the last item for which it returns true is returned.
$$defaultoptionalmixed= nullValue returned when nothing matches. A closure is resolved, so the fallback can be computed lazily.

Return value

mixedThe last matching item, or the default when the collection is empty or nothing matches.

last returns the item at the end of the collection. Given a callback, it instead returns the last item for which the callback returns true — internally the array is reversed (keys preserved) and the first match is taken, so the callback still receives ($value, $key) with the original key.

When to reach for it

Reading the newest row out of a chronologically ordered result, taking the final segment of a parsed path, or grabbing the most recent entry that satisfies a condition — the last failed attempt, the last completed step. The callback form saves you a filter() that would build an entire intermediate collection just so you could discard all but one item.

What trips people up

It returns the value, not a collection, so the chain stops there. On an empty collection or with no match it returns null unless you supply a default, which means $c->last()['id'] can blow up on an empty result. The default may be a closure, and it is only invoked when it is actually needed. Finally, "last" means last in the collection's current order — if the underlying query was not sorted, the answer is whatever order the data happened to arrive in.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Read the most recent status entry from a chronologically ordered log collection.
  • Find the last failed attempt in a list of job attempts without filtering the whole set.
  • Take the final segment of an exploded path or version string.

Frequently asked questions

How do I get the last element of a Laravel collection?

Call $collection->last() with no arguments; it returns the value at the end of the collection, or null when the collection is empty.

How is it different from reverse()->first()?

The result is the same, but this method does the reversal internally on the raw array and stops at the first match, so it does not build an intermediate reversed collection.

Can I return something other than null when nothing matches?

Yes — pass a second argument as the default. If that argument is a closure it is only called when the fallback is actually needed.

More examples

The callback sees the key too

The truth test receives both the value and the key, but the method still returns the value — 'done'. When you need the key instead, run the search over keys(), which prints 'install'.

Example · php
<?php

$steps = collect([
    'clone' => 'done',
    'install' => 'done',
    'test' => 'failed',
    'deploy' => 'skipped',
]);

$lastDone = $steps->last(fn (string $state, string $name) => $state === 'done');

echo $lastDone . PHP_EOL;

$lastDoneName = $steps->keys()->last(
    fn (string $name) => $steps->get($name) === 'done'
);

echo $lastDoneName . PHP_EOL;

A lazy default

The default is passed through value(), so a closure is only executed when there is nothing to return. The first call prints the fallback; the second prints the real last row and never runs the closure.

Example · php
<?php

$attempts = collect([]);

$latest = $attempts->last(default: fn () => ['status' => 'never run']);

print_r($latest);

$withMatches = collect([
    ['status' => 'ok'],
    ['status' => 'failed'],
])->last(default: fn () => ['status' => 'never run']);

print_r($withMatches);

In an application, after ordering

"Last" is positional, so the sort is what makes the answer meaningful. The nullsafe operator handles the case where the customer has never paid an invoice — this snippet assumes Eloquent models and so is shown rather than executed.

Example · php
<?php

$invoice = $customer->invoices
    ->sortBy('issued_at')
    ->last(fn ($invoice) => $invoice->status === 'paid');

echo $invoice?->reference ?? 'no paid invoices';

Discussion

  • Be the first to comment on this lesson.