Skip to content

Commit

Permalink
Merge pull request #27985 from rodrigopedra/resources-keys
Browse files Browse the repository at this point in the history
[5.8] Check for preserveKeys when serializing a collection from a resource
  • Loading branch information
taylorotwell authored Mar 29, 2019
2 parents 694d566 + 502492e commit 16f68bb
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Illuminate/Http/Resources/Json/JsonResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ public static function make(...$parameters)
*/
public static function collection($resource)
{
return new AnonymousResourceCollection($resource, static::class);
return tap(new AnonymousResourceCollection($resource, static::class), function ($collection) {
if (property_exists(static::class, 'preserveKeys')) {
$collection->preserveKeys = (new static([]))->preserveKeys === true;
}
});
}

/**
Expand Down
34 changes: 34 additions & 0 deletions tests/Integration/Http/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Tests\Integration\Http;

use Orchestra\Testbench\TestCase;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Resources\MergeValue;
use Illuminate\Http\Resources\MissingValue;
Expand Down Expand Up @@ -629,6 +630,39 @@ public function test_keys_are_preserved_if_the_resource_is_flagged_to_preserve_k
$response->assertJson(['data' => $data]);
}

public function test_keys_are_preserved_in_an_anonymous_colletion_if_the_resource_is_flagged_to_preserve_keys()
{
$data = Collection::make([
[
'id' => 1,
'authorId' => 5,
'bookId' => 22,
],
[
'id' => 2,
'authorId' => 5,
'bookId' => 15,
],
[
'id' => 3,
'authorId' => 42,
'bookId' => 12,
],
])->keyBy->id;

Route::get('/', function () use ($data) {
return ResourceWithPreservedKeys::collection($data);
});

$response = $this->withoutExceptionHandling()->get(
'/', ['Accept' => 'application/json']
);

$response->assertStatus(200);

$response->assertJson(['data' => $data->toArray()]);
}

public function test_leading_merge_keyed_value_is_merged_correctly()
{
$filter = new class {
Expand Down

0 comments on commit 16f68bb

Please sign in to comment.