Skip to content

Support map(...)->toJson() with collections #1286

@innocenzi

Description

@innocenzi

My use case is using the mapper to serialize an array of models (from the database) to JSON.

// get items
$items = query(DebugItem::class)
  ->select()
  ->all();

// convert to json
map($items)->toJson();

The above example works but the registered serializers are not used. Under the hood, json_encode is used. I'd like this to work:

map($items)->collection()->toJson();

My current workaround is something like that, but the underlying properties are not converted to arrays, they are still json-encoded strings:

$result = [];

foreach ($items as $item) {
    $result[] = map($item)->toArray();
}

dd(Json\encode($result));

FYI, my model is this:

final class DebugItem
{
    public function __construct(
        public int $id,
        #[DateTimeFormat(FormatPattern::JAVASCRIPT)]
        public DateTime $created_at,
        public ?string $request_id,
        public DebugItemType $type,
        public string $data,
        public Backtrace $backtrace,
    ) {}
}

Metadata

Metadata

Assignees

Labels

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions