Gardezi
Gardezi

Reputation: 2842

Getting last element of the Collection

guys, I'm trying to get the last element from the data returned to me but the problem is that it is throwing me an error which is

Call to undefined method Illuminate\Database\Query\Builder::last()

Here is my code

$last_saved_snapshot = \EnginePerformanceTestSnapshot::where('engine_performance_test_id', $id)->last();

Please tell me what is it that I'm doing wrong. Thanks

P.S I'm using Laravel 5.0

Upvotes: 14

Views: 46610

Answers (4)

Jorge Y. C. Rodriguez
Jorge Y. C. Rodriguez

Reputation: 3449

The last method call is not working because namespace Illuminate\Database\Eloquent; does not have any last() method. The right way to do this is to do something like this:

$last_saved_snapshot = EnginePerformanceTestSnapshot::query()
    ->where('engine_performance_test_id', $id)
    ->orderBy('id', 'desc')
    ->first();

Otherwise, you need to get all items, since last() is part of the collection class so it expects a collection or array to be able to work and not a query builder. It is less efficient and a bad practice to fetch all data just for one.

Upvotes: 10

Darlan Dieterich
Darlan Dieterich

Reputation: 2537

Try this, less code:

\EnginePerformanceTestSnapshot::
    where('engine_performance_test_id', $id)
    ->latest()
    ->first();

Upvotes: 4

Marek Skiba
Marek Skiba

Reputation: 2184

Try something like that:

$last_saved_snapshot = \EnginePerformanceTestSnapshot::where('engine_performance_test_id', $id)
    ->get()
    ->last();

Upvotes: 24

Gardezi
Gardezi

Reputation: 2842

I found another way to do it and that is:

$last_saved_snapshot = \EnginePerformanceTestSnapshot::where('engine_performance_test_id', $id)->orderBy('id', 'desc')->first();

This is working but if somebody can tell me why is the last not working then that would be a great help. Thanks

Upvotes: 5

Related Questions