Replies: 2 comments
-
I found a solution but it required extending some classes and overriding some methods. Maybe there is an easier way or someone has ideas for a PR to make this easier. Set a custom paginated collection class class NotificationData extends Data
{
// custom paginated collection class
protected static string $paginatedCollectionClass = CjPaginatedDataCollection::class;
public function __construct(
public int $id,
public Carbon $createdAt,
public bool $unread,
public NotificationMemberData|Optional $member,
public string $message,
public array $data,
) {
}
} Extend the base class CjPaginatedDataCollection extends PaginatedDataCollection
{
public function transform(
bool $transformValues = true,
WrapExecutionType $wrapExecutionType = WrapExecutionType::Disabled,
bool $mapPropertyNames = true,
): array {
$transformer = new CjDataCollectableTransformer(
$this->dataClass,
$transformValues,
$wrapExecutionType,
$mapPropertyNames,
$this->getPartialTrees(),
$this->items,
$this->getWrap(),
);
return $transformer->transform();
}
} Extend the base class CjDataCollectableTransformer extends DataCollectableTransformer
{
public function transform(): array
{
if ($this->items instanceof Enumerable) {
return $this->transformCollection($this->items);
}
$this->items->through(
$this->transformItemClosure()
);
return $this->transformValues
//? $this->wrapPaginatedArray($this->items->toArray())
? $this->wrapPaginator($this->items)
: $this->items->all();
}
protected function wrapPaginator(Paginator $paginator): array
{
$wrapKey = $this->wrap->getKey() ?? 'data';
$currentPage = $paginator->currentPage();
return [
$wrapKey => $paginator->toArray()['data'],
'meta' => [
'pagination' => [
'count' => $paginator->count(),
'per_page' => $paginator->perPage(),
'prev_page' => $currentPage <= 1 ? null : $currentPage - 1,
'current_page' => $currentPage,
'next_page' => $paginator->hasMorePages() ? $currentPage + 1 : null,
],
],
];
}
} |
Beta Was this translation helpful? Give feedback.
-
Has anyone found a cleaner solution for this in 2024? Also, thank you so much @ejunker, saved me hours potentially. |
Beta Was this translation helpful? Give feedback.
-
I'm still new to laravel-data so I am not sure if this is possible. I would like to customize how paginator objects are transformed. Specifically the
meta
object. I have an API that usesleague/fractal
and it formats the pagination data different and I would like to replace Fractal with laravel-data but keep the same response format.Desired format for the
meta
section:Additionally, is there a way to add custom data to the
meta
object?Beta Was this translation helpful? Give feedback.
All reactions