Alen
Alen

Reputation: 1788

Select last rows in ascending order

I'm trying to select last 5 messages in ascending order (Laravel) but I'm receiving this error: Call to undefined method Illuminate\Database\Query\Builder::reverse()

This is what I've tried:

$messages = Conversation::find($id)->messages()->orderBy("created_at", "desc")->take(5)->reverse();

Upvotes: 2

Views: 1098

Answers (1)

ollieread
ollieread

Reputation: 6301

The problem is that you aren't ever running the query. The take() method is a query builder method rather than a return method.

  • get() Is a return method, it will run the query return a collection
  • first() Is a return method, it will run the query and return a model instance

It's also worth noting that reverse() is a collection method, so to fix your code, you'd need to do the following:

$messages = Conversation::find($id)->messages()->orderBy("created_at", "desc")->take(5)->get()->reverse();

That will work perfectly, although I would recommend checking the value before actually running a method on it, but other than that, you're good to go.

Upvotes: 3

Related Questions