inertia-laravel icon indicating copy to clipboard operation
inertia-laravel copied to clipboard

[1.x] Fix resolving response arrayable properties

Open VicGUTT opened this issue 1 year ago • 1 comments

Prior to https://github.com/inertiajs/inertia-laravel/pull/620, property instances were resolved before handling arrayable/array values when sending a response.

Consider the following Inertia response dump:

AsArrayable
use Illuminate\Contracts\Support\Arrayable;

class AsArrayable implements Arrayable {
    public function __construct(private array $data) {}

    public static function make(array $data): static {
        return new static($data);
    }

    public function toArray(): array {
        return $this->data;
    }
}
use Inertia\Inertia;
use Illuminate\Http\Request;

$request = Request::create('/auth', 'GET');

$response = Inertia::render('auth', [
    'user' => fn () => [
        'full_name' => 'Victor Gutt',
        'organizations' => AsArrayable::make([
            fn () => [
                'name' => 'Transl.me',
            ],
        ]),
    ],
]);

$response = $response->toResponse($request);

dd(
    $response->original->getData()['page']['props'],
);

Before this fix, the dump would be similar to:

Inertia\Tests\ResponseTest
array:1 [
  "user" => array:2 [
    "full_name" => "Victor Gutt"
    "organizations" => Inertia\Tests\Stubs\AsArrayable {#1291
      #data: array:1 [
        0 => Closure() {#1277
          class: "Inertia\Tests\ResponseTest"
          this: Inertia\Tests\ResponseTest {#173 …}
        }
      ]
    }
  ]
]

As we can see, nested (user.organizations) arrayable values are no longer resolved.

After this fix, the dump is similar to:

Inertia\Tests\ResponseTest
array:1 [
  "user" => array:2 [
    "full_name" => "Victor Gutt"
    "organizations" => array:1 [
      0 => array:1 [
        "name" => "Transl.me"
      ]
    ]
  ]
]

This PR aims to bring back the behaviour prior to #620.

VicGUTT avatar May 29 '24 11:05 VicGUTT