As emergency teams worked tirelessly to free the boy over the past five days, the effort was livestreamed across the world, gripping thousands who prayed for Rayan's safe rescue.
The boy was fed water with sugar and also received oxygen during his time trapped in the narrow well.
Rayan fell down the narrow 32m deep well on Wednesday in his home village near Bab Berred in the rural Northern Province of Chefchaouen, local media said.
The shaft was too narrow for rescuers to reach the bottom, so heavy diggers were dispatched to dig a hole alongside it.
Rayan's father told Le360 news website he had been repairing the well when the boy fell into it.
Lead rescuer Abdelhabi Temrani told Al Oula television the diameter of the well was less than 45cm.
The drama sparked an outpouring of sympathy online; the Arabic hashtag #SaveRayan went viral across North Africa and people followed the rescue worldwide via social media.