Open ennorehling opened 1 month ago
@ennorehling It seems necessary to append toArray()
or a similar method in the Spatie\LaravelData\Concerns\TransformableData
class. After the transformation, the data will be properly wrapped.
I think my report is simply bad, owing to my trying to match the format of the reporting template.
What I'm actually doing is, I return this from a resource controller, roughly like this:
public function store(Request $request)
{
$result = UserData::from(['name' => $request->validated('name')]);
return $result->additional(['role' =>$request->validated('role')])->wrap('data');
}
my failing test looks something like this:
$values = ['name => 'Ruben', 'role' => 'admin'];
$this->post('/users', $values)->assertJson(['data' => $values]);
I don't see where adding a toArray()
anywhere in here would make a difference.
Thank you for explaining. I understand your perspective now. During detailed debugging, I discovered that the wrap behavior is designed to work as seen in this test case:
[
"data" => [
"name" => "Ruben",
],
"rank" => "admin",
]
I then reviewed the documentation regarding wrapping and appending:
Wrapping:
By default, when a data object is transformed into JSON in your controller... It is possible to wrap a data object.
Appending properties:
It is possible to add some extra properties to your data objects when they are transformed into a resource.
Based on this, it seems more reasonable for the wrap to behave as you expected:
[
"data" => [
"name" => "Ruben",
"rank" => "admin",
],
]
Therefore, I opened a PR to adjust the behavior when both wrap and additional are present. Appreciate that maintainer could review and leave an opinion.
✏️ Describe the bug When adding additional properties to a Data Object, they do not get wrapped by wrap().
↪️ To Reproduce Provide us a pest test like this one which shows the problem:
Assertions aren't required, a simple dump or dd statement of what's going wrong is good enough 😄
✅ Expected behavior I'm expecting this to produce
but instead, I get [ "data" => [ "name" => "Ruben", ], "rank" => "admin", ]
A similar thing happens when I add a with() method to the object.
🖥️ Versions
Laravel: v10.48.22 Laravel Data: 4.11.0 PHP: 8.2.20