Posted on • Updated on

Difference Between "sortBy" and "orderBy" in Laravel

author

Kai

#sortBy

The sortBy method sorts the collection by the given key.

We sort / arrange the fetched data in descending order according to the "id" of the data using sortByDesc("id"). 

dd(Enquiry::all()->sortBy("id", "desc")); 
//OR
dd(Enquiry::all()->sortByDesc("id")); 

Note that the sort function cannot be used before "all()" or "get()".

#orderBy

If we use "orderBy()" rather than "sortBy()." 

We sort / arrange the Data before fetching it in descending order according to the "id" of the data using orderBy('id', 'desc'). 

//Ascending order
dd(Enquiry::orderBy("id")->get());  
//Descending order
dd(Enquiry::orderBy("id", "desc")->get());

#Conclusion

If you noticed the Output Index value of the child objects of the Fetched array "#items". Both methods return a collection of data but in different order of index values. 

end of article

Related Posts

Join Our Newsletter

Want the latest & greatest from our blog straight to your inbox with some exclusive offers from our partners and sponsors?

We won't spam. Promise.