Hello, I am trying to work out how to add a new key value pair at the top level of a paginated collection. I have been trying to work this out, as I have an object that has been flashed to the session in a method that redirects back to the method in which I am trying to inject it's values into the paginated collection. I can have worked out how to add it to each item in the collection.data, using the following:
// map the collection to be returned and add the 'new' key to the array at the top level
$threads->getCollection()->transform(function ($thread) {
return array_merge($thread, ['new' => (bool)session('show'),]);
});
However, this is annoying as it is adding it to each item & will return way more data than I need.
I had the idea that maybe paginating the collection after the query has been performed & somehow injecting the key value pair at this point, but I would not know how to do that either.
I really need to work this out, can you help me?
This is the full method currently:
public function index()
{
$threads = Thread::query()
->select('*')
->with('creator:id,username,email')
->with(['replies' => function ($query) {
$query->select('replies.id', 'replies.thread_id', 'replies.body', 'replies.created_at', 'replies.updated_at', 'replies.user_id')
->with('owner:id,username,email')
->leftJoin('users', 'users.id', '=', 'replies.user_id');
}])
->latest()
->paginate(20)
->through(function ($thread) {
$firstReply = $thread->replies->first();
return [
'title' => $thread->title,
'body' => $thread->body,
'slug' => $thread->slug,
'views' => $thread->views,
'solved' => $thread->solved,
'created_at' => $thread->created_at->diffForHumans(null),
'replies' => $thread->replies->count() ? [
'count' => $thread->replies->count(),
'first' => [
'body' => $firstReply->body,
'created_at' => $firstReply->created_at->diffForHumans(null),
'updated_at' => $firstReply->updated_at->diffForHumans(null),
'owner' => [
'username' => $firstReply->owner->username,
'email' => $firstReply->owner->email,
]
],
] : null,
'creator' => [
'username' => $thread->creator->username,
'email' => $thread->creator->email,
],
];
});
// map the collection to be returned and add the 'new' key to the array at the top level
$threads->getCollection()->transform(function ($thread) {
return array_merge($thread, ['new' => (bool)session('show'),]);
});
return Inertia::render('Discussion/Index', [
'conversations' => $threads,
]);
}