I would assume that you want to sort from the collection resource? Here you have just 1 item
Dec 22, 2021
9
Level 12
How to sort collection resource using the index
I'm trying to use collection resource, and need to sort the data by commented_at index. I tried using rsort to sort the collection but still not working. Please see the code below.
Problem:
The data is not showing sorted using the commented_at descending, it is still showing in ascending order.
Resources/CommentCollection.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CommentCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection,
'comment_count' => $this->count(),
'links' => [
'self' => url('/posts')
]
];
}
}
Resources/Comment.php
<?php
namespace App\Http\Resources;
use App\Http\Resources\User as UserResource;
use Illuminate\Http\Resources\Json\JsonResource;
class Comment extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return rsort([
'data' => [
'type' => 'comments',
'comment_id' => $this->id,
'attributes' => [
'commented_by' => new UserResource($this->user),
'body' => $this->body,
'commented_at' => $this->created_at->diffForHumans()
]
],
'links' => [
'self' => url('/posts/' . $this->post_id)
]
]);
}
}
Error:
"Cannot pass parameter 1 by reference"
[SOLUTION]:
- Just added
->sortByDesc('created_at')->values()->all(). - Modified the
CommentCollection.phpto this code:
public function toArray($request)
{
return [
'data' => $this->collection->sortByDesc('created_at')->values()->all(),
'comment_count' => $this->count(),
'links' => [
'self' => url('/posts')
]
];
}
Level 102
Or sort it when you get it from the database (what I would do)
1 like
Please or to participate in this conversation.