John Davidson

php - laravel - orderby doesn't show correct results

0 comments
Message:


I have a fairly simple query which I load and add an element to the object and then sort it based on that custom element. I'd like to take 20 records or paginate it but when I do so, alot of data vanishes.


This is my code. The piece below gets all the records.


$fighters = Fighter::all();


The below code gets the points which is in a function and adds it to the fighter, fighterPoints does not initially exist in the collection, it is created and populated below.


foreach ($fighters as $fighter) {
$fighter->fighterPoints = $fighter->getFighterPoints($fighter->id);
}

Then i'd like to sort everything by those fighterPoints with the below function.


$sorted = $fighters ->sortByDesc(function ($item, $key) {
return $item->fighterPoints ;
});

When i do this i get all the records which are around 9000, it then sorts on the fighterPoints correctly:
The first record being something like [FighterName, 21309]


When i do $fighters = Fighter::paginate(20); it simply starts with [FighterName384, 200] which should be [FighterName, 21309] and just 20 results. The same thing happens with ::take(20) method.


What am I doing wrong here? I am laravel 8.



My Answer:
In Laravel, you can use the `orderBy` method to sort the results of a query by a specific column.

Here's an example of how you can use the `orderBy` method in Laravel:

php
$users = User::orderBy('name', 'asc')->get();


In this example, we are sorting the `users` collection by the `name` column in ascending order. You can also specify the sorting order by passing `asc` for ascending order or `desc` for descending order.

You can also sort by multiple columns by chaining multiple `orderBy` methods:

php
$users = User::orderBy('name', 'asc')->orderBy('created_at', 'desc')->get();


This will first sort the `users` collection by the `name` column in ascending order, and then by the `created_at` column in descending order.

You can also use the `latest` and `oldest` methods to sort by the `created_at` column:

php
$users = User::latest()->get(); // Sort by created_at column in descending order
$users = User::oldest()->get(); // Sort by created_at column in ascending order


These are some of the ways you can use the `orderBy` method in Laravel to sort query results.

Rate this post

5 of 5 based on 1132 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us