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.
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.
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.
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.
Use this to reset the keys:
->reverse()->values();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With