Skip to content

Commit

Permalink
Make DataCollection JsonSerializeable
Browse files Browse the repository at this point in the history
  • Loading branch information
rubenvanassche committed Jan 19, 2022
1 parent 2b7fab8 commit 6e6e40e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/DataCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Illuminate\Support\Enumerable;
use Illuminate\Support\LazyCollection;
use IteratorAggregate;
use JsonSerializable;
use Spatie\LaravelData\Concerns\IncludeableData;
use Spatie\LaravelData\Concerns\ResponsableData;
use Spatie\LaravelData\Exceptions\CannotCastData;
Expand All @@ -24,7 +25,7 @@
use Spatie\LaravelData\Support\TransformationType;
use Spatie\LaravelData\Transformers\DataCollectionTransformer;

class DataCollection implements Responsable, Arrayable, Jsonable, IteratorAggregate, Countable, ArrayAccess, EloquentCastable
class DataCollection implements Responsable, Arrayable, Jsonable, JsonSerializable, IteratorAggregate, Countable, ArrayAccess, EloquentCastable
{
use ResponsableData;
use IncludeableData;
Expand Down Expand Up @@ -95,6 +96,11 @@ public function toJson($options = 0): string
return json_encode($this->toArray(), $options);
}

public function jsonSerialize(): array
{
return $this->toArray();
}

public function toCollection(): Enumerable
{
if ($this->isPaginated()) {
Expand Down
9 changes: 9 additions & 0 deletions tests/DataCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -386,4 +386,13 @@ public function it_can_convert_a_data_collection_into_a_laravel_collection()
SimpleData::collection(['A', 'B', 'C'])->toCollection()
);
}

/** @test */
public function a_collection_can_be_transformed_to_json()
{
$collection = SimpleData::collection(['A', 'B', 'C']);

$this->assertEquals('[{"string":"A"},{"string":"B"},{"string":"C"}]', $collection->toJson());
$this->assertEquals('[{"string":"A"},{"string":"B"},{"string":"C"}]', json_encode($collection));
}
}

0 comments on commit 6e6e40e

Please sign in to comment.