Gandalf was able to save the dwarves from the trolls in The Hobbit because he cleverly confuses the trolls until dawn.
From the story, it should be noted that the dwarves will have been killed by the trolls if not for the help of Gandalf.
This wasn't because he magically casts a sleeping spell on them but rather because he cleverly confuses the trolls until dawn. Then, after confusing them, the dwarves escaped.