Home > Software engineering >  Method Illuminate\\\\Support\\\\Collection::latest does not exist
Method Illuminate\\\\Support\\\\Collection::latest does not exist

Time:05-01

I'm trying to append a last_messages accessor to my Chat model forappending last 10 messages, however I'm getting this error:

Method Illuminate\\\\Support\\\\Collection::latest does not exist.

My accessor code, wich I append using $appends

protected $appends = ['has_unread','last_messages'];

public function getLastMessagesAttribute()
    {
        //return collect($this->messages)->latest('created_at')->first();
        return collect($this->messages)->latest('created_at')->take(10)->get();
    }

CodePudding user response:

If this is a one-to-many relation so you could do that like this by removing the collect method

public function getLastMessagesAttribute()
    {
        return $this->messages()->latest('created_at')->take(10)->get();
    }

CodePudding user response:

latest() is an Eloquent method for queries that essentially asks the database to orderBy('created_at', 'desc').

Unfortunately, this method does not exist on the Laravel collection (thus the error message).

You can, however, make this work the way you want, using a different method on your collection.

Try:

return collect($this->messages)->sortBy('created_at');

You can get pretty crafty with sortBy, creating virtually anything you want using a closure:

$x = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
});

The base method also takes a variety of standard PHP sort flags to make life easy. E.g.:

$collection->sortBy('title', SORT_NATURAL);

Check the Laravel docs on this for a little more detail.

CodePudding user response:

I think you are importing the wrong class.

Try to import this one -> Illuminate\Database\Eloquent\Collection. In that class, a method called latest exists.

  • Related