The phrase suggests that everything that happens, no matter how seemingly negative or unfortunate, is ultimately part of a divine or perfect plan and is for the best in the grand scheme of things.
All is for the best" in the "best of all possible worlds". Candide. The title-page of the 1759 edition published by Cramer in Geneva, which reads, "Candide: or, All for the Best.