Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zagreus's avatar

Serialize includes array

We can eager load relationships like this

$books = Book::with([
    'author' => [
        'contacts',
        'publisher',
    ],
])->get();

and then include them optionally in our resources like this: $this->whenLoaded(

What i'd like to do is pass a list of includes in my api url so that the client can decide which relationships it needs. I don't want to use the native PHP serialize because it is quite heavy and difficult to build outside of PHP (i.e. in a JS client or for a curl call). I can't use json encoding because you can mix array types (in php you can have this [ "image", "grouping" => [ "users" => ["image", "address"], "invitations" ] however JSON would require a key for each element including the leaves of this tree (like image, invitations, address).

Has anyone found a way to do anything similar? I'd like to use something like this image,grouping(users(image,address),invitations) but am struggling to find a way to do it.

0 likes
0 replies

Please or to participate in this conversation.