skip to Main Content

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 ?

2

Answers


  1. 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');
    
    Login or Signup to reply.
  2. Instead of latest() make a sortition in a descending order and simply take as many as you need.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search