The riddle
Why Did the Student Eat His Homework?
An idiom taken literally
Piece of cake is an idiom. Wiktionary defines it as a job, task or other activity that is pleasant or, by extension, easy or simple. Literally it is a slice of dessert. A teacher who calls an assignment a piece of cake means it will be easy, and the student in the riddle hears it as an instruction to eat.
Dated to 1936
Wiktionary says the phrase is attested since 1936, originally in American English. It offers two possible sources and settles on neither: the cakewalk, or the idea that cakes taste agreeable and so are easy to take in. Wiktionary lists easy as pie as a related term, another dessert comparison. It also compares French, where being "of the cake" or "of the pie" means the same as being easy.
Why only cake works
English has many ways to say a task is easy. Wiktionary lists breeze, cinch, child's play and walk in the park, and none of those can be eaten. The riddle depends on an idiom whose second word is a food, so swapping in a different synonym ruins it. A group can test this by retelling the joke with each one and noting where it falls flat.
A school setting
Homework is simply home plus work, per Wiktionary. A teacher gives it, and the joke has the teacher as the one who unwittingly made the suggestion. For another riddle set in a classroom, try why was the math book sad.