'Laravel pluck didnot return sort array as database
I use Laravel 5.8 for my project. I want to get an array with 'id' of table. So I use Laravel Collection - pluck method for this problem.
This is my database.

App\User::pluck('id')->all()
=> [ 3, 1, 4, 2]
Why doesn't it return [1, 2, 3, 4]??
So I tried App\User::all()->pluck('id')
Wow, it returned [1, 2, 3, 4].
Why does the second work??
Solution 1:[1]
The difference in the results of these two queries is caused by how eloquent interprets you wanting to use the data. In both cases the query that gets run against your database is an unconstrained select statement, if you run the pluck first it only selects the id field, if you run the all() first it selects all fields.
The result that gets returned from mysql has no default order. If you do not specify an order in your SQL query, SQL decides the order the records are returned in and it is inconsistent and non-determinant
So in the first example the results are returned in whatever order MySQL decides and immediately added to an array because that's all you asked for. The order of the values of the array is the same as whatever gets returned from the SQL query.
In the second example, Eloquent turns the values it gets back from the database into instances of User::class and puts them into a collection. When an eloquent collection contains model instances, it's sorted by id unless you specify otherwise. You then perform the pluck method which grabs just the id and keeps them in the same order.
Solution 2:[2]
App\User::select('id')->orderBy('id')->get();
Solution 3:[3]
By using the orderBy method before the pluck method you can sort an array. Please have a look at the below example.
App\User::orderBy('id', 'DESC')->pluck('id');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Serhii Posternak |
| Solution 3 | Soubhagya Kumar Barik |
