Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse() on querybuilder get() changes the collection results

I need to get last 10 records of a table ordered by a data, and reverse them.

This is the code before the reverse:

$eventi = \App\Model::with('relation_1', 'relation_2')
    ->orderBy('data_ora', 'desc')
    ->take(10)
    ->get();

If I log the results I get this:

[{"id":12297,"stato_batteria":null,"data_ora":"2018-05-03 11:40:02" ...

The reverse code is:

$eventi = \App\Model::with('relation_1', 'relation_2')
    ->orderBy('data_ora', 'desc')
    ->take(10)
    ->get()
    ->reverse();

If I log the results I get this:

{"9":{"id":1410,"stato_batteria":null,"data_ora":"2018-04-05 14:16:48" ...

As you can see the collection is changed and I do not know why.

like image 673
Giacomo M Avatar asked May 03 '18 10:05

Giacomo M


People also ask

What is the use of pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

How to use collections in Laravel?

Creating Collections As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as: $collection = collect([1, 2, 3]); The results of Eloquent queries are always returned as Collection instances.

How to sorting data in Laravel?

To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.


1 Answers

Use this to reset the keys:

->reverse()->values();
like image 76
Jonas Staudenmeir Avatar answered Nov 25 '22 01:11

Jonas Staudenmeir