You can actually do this within the query.
$results = Project::orderBy('name')->get();
This will return all results with the proper order.
You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.
Ascending Order
$results = Project::all()->sortBy("name");
Descending Order
$results = Project::all()->sortByDesc("name");
Check out the documentation about Collections for more details.
https://laravel.com/docs/5.1/collections
In addition, just to buttress the former answers, it could be sorted as well either in descending desc
or ascending asc
orders by adding either as the second parameter.
$results = Project::orderBy('created_at', 'desc')->get();
DO THIS:
$results = Project::orderBy('name')->get();
Why? Because it's fast! The ordering is done in the database.
DON'T DO THIS:
$results = Project::all()->sortBy('name');
Why? Because it's slow. First, the the rows are loaded from the database, then loaded into Laravel's Collection class, and finally, ordered in memory.
Laravel 5.4 added orderByDesc() methods to query builder:
$results = Project::orderByDesc('name')->get();
While you need result for date as desc
$results = Project::latest('created_at')->get();
Check out the sortBy
method for Eloquent: http://laravel.com/docs/eloquent
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