Home > other >  Why can't I use latest() in my Eloquent code?
Why can't I use latest() in my Eloquent code?

Time:04-15

I have been getting an error 'Method Illuminate\Database\Eloquent\Collection::latest does not exist' on this line of my code

     $items=Item::select('*')
    ->orderBy('version','DESC')
    ->get()
    ->unique('name')->latest()->paginate(5);

I'm not really sure why and how should I change my code?

CodePudding user response:

Laravel's latest method doesn't work on the collection, it works on Query-Builder. So, first, use the latest method and then use paginate.

$items = Item::select('*')
     ->orderBy('version','DESC')
     ->latest()
     ->paginate(5)
     ->unique('name');

CodePudding user response:

latest() is a Builder class method not a Collection class method see: https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Builder.html#method_latest

So use it before getting the collection by get() or paginate():

$items=Item::select('*')
    ->orderBy('version','DESC')
    ->latest()
    ->get()
    ->unique('name');

Using pagination on unique values is a bit more complicated. We would need to know what to select if there is more records with the same name. The most simple approach is to use distinct() but this may not be what you need:

$items=Item::select('*')
    ->orderBy('version','DESC')
    ->latest()
    ->distinct()
    ->paginate(5);

Other possibility is to use groupBy('name') instead of distinct(), but there you must carefully aggregate the other columns around the 'name' (or select only the 'name' column).

  • Related