#[Groups] in Symfony: choosing the fields the Serializer publishes

The #[Groups] attribute of the Symfony Serializer sorts a class's properties into groups: you ask for a group, and only its properties are published.

class Plat
{
    #[ORM\Column]
    #[Groups(['carte'])]
    private ?float $prix = null;

    #[ORM\ManyToOne]
    private ?Employe $createur = null; // no group: never published
}

// In the controller:
return $this->json($platRepository->findParPrixCroissant(), context: ['groups' => ['carte']]);

Without a requested group, the Serializer publishes everything its getters expose, relations included. With context: ['groups' => [...]], it reverses the logic: nothing goes out without being invited, and a tagged relation in turn only exposes the properties of the same group in the linked class. A property can belong to several groups, and so can a computed getter, so that a detailed page shows more than the list. The trap: the group name is a plain string. A typo, cartes instead of carte, and the property vanishes from the response without the slightest error; forget the context, and everything comes back.

The exercises have you publish the tavern's menu exposing only what is needed, category included, creator excluded, then track down, in a sabotaged API, prices that have evaporated and a booking that says far too much.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

JSON APISerializerDebuggingFirewall