Skip to content

Commit b6fc35b

Browse files
committed
Return an encoded empty array when formatting empty Eloquent collection. Fixes dingo#4.
Signed-off-by: Jason Lewis <[email protected]>
1 parent f31951f commit b6fc35b

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

src/Http/ResponseFormat/JsonResponseFormat.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ public function formatEloquentModel($model)
2525
*/
2626
public function formatEloquentCollection($collection)
2727
{
28+
if ($collection->isEmpty())
29+
{
30+
return $this->encode([]);
31+
}
32+
2833
$key = str_plural($collection->first()->getTable());
2934

3035
return $this->encode([$key => $collection->toArray()]);

tests/HttpResponseFormatJsonResponseFormatTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ public function testMorphingEloquentCollection()
3737
}
3838

3939

40+
public function testMorphingEmptyEloquentCollection()
41+
{
42+
$response = with(new Response(new EmptyEloquentCollectionStub))->morph();
43+
44+
$this->assertEquals('[]', $response->getContent());
45+
}
46+
47+
4048
public function testMorphingJsonableInterface()
4149
{
4250
$response = with(new Response(new JsonableStub))->morph();

tests/stubs.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public function toArray()
1212

1313
}
1414

15+
1516
class EloquentCollectionStub extends Illuminate\Database\Eloquent\Collection {
1617

1718
public function __construct()
@@ -24,6 +25,12 @@ public function __construct()
2425

2526
}
2627

28+
29+
class EmptyEloquentCollectionStub extends Illuminate\Database\Eloquent\Collection {
30+
31+
}
32+
33+
2734
class JsonableStub implements Illuminate\Support\Contracts\JsonableInterface {
2835

2936
public function toJson($options = 0)

0 commit comments

Comments
 (0)