I have 6 data in database record but I want to get last 3 data
this is my data :
| criteria_id | criteria_name |
|---|---|
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
| 6 | F |
i have tried with this code :
$criteria= criteria::latest()->take(3)->get();
but i got data like this :
| criteria_id | criteria_name |
|---|---|
| 6 | F |
| 1 | A |
| 2 | B |
and I also tried with orderby the result is like this :
| criteria_id | criteria_name |
|---|---|
| 6 | F |
| 5 | E |
| 4 | D |
the result should be like this, i want this result :
| criteria_id | criteria_name |
|---|---|
| 4 | D |
| 5 | E |
| 6 | F |
how can i get data like last result ?
>Solution :
Your row would need a created_at column to use latest(), but what you have would work. Alternatively, you could sort on the criteria_id column, then take 3.
Criteria::orderBy('criteria_id', 'desc')->take(3)->get();
Edit: Just saw your changes. Just do the above then add a sortBy on the collection
Criteria::orderBy('criteria_id', 'desc')->take(3)->get()->sortBy('criteria_id');