Rejaul
Rejaul

Reputation: 980

Get last few rows in ascending order in Laravel

What is the best way (Laravel way) to get last few rows of a database table in ascending order? I want the result to be an array of objects as like:

[{"name1":"value1"}, {"name2":"value2"}]

My recent code is like:

$users = User::take(2)->latest()->get()->reverse();
return $users;

Output looks like:

{"1":{"id":582, "name":"name1"}, "0":{"id":583, "name":"name2"}}

But I want the output to be like:

[{"id":582, "name":"name1"}, {"id":583, "name":"name2"}]

Upvotes: 1

Views: 72

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29316

When you use the reverse() method, it modifies the Collection, but doesn't re-index it, meaning the Collection is now [1, 0]. JS/JSON treats this as an Object instead of an array, hence the difference:

{"1":{"id":582, "name":"name1"}, "0":{"id":583, "name":"name2"}}
// VS
[{"id":582, "name":"name1"}, {"id":583, "name":"name2"}]

To solve this, use the values() method to re-index the array before return:

$users = User::take(2)->latest()->get()->reverse();
return $users->values();
// [{"id":582, "name":"name1"}, {"id":583, "name":"name2"}]

If you want them in the other order, don't use reverse(), and you shouldn't need values() either:

$users = User::take(2)->latest()->get();
return $users;
// [{"id":583, "name":"name2"}, {"id":582, "name":"name1"}]

Upvotes: 1

Related Questions