Let $\mathscr L (\phi(\mathbf x), \partial \phi(\mathbf x))$ denote the Lagrangian density of field $\phi(\mathbf x)$. Then then actual value of the field $\phi(\mathbf x)$ can be computed from the principle of least action. In case of motion of particles, I know that principle of least action comes from Newton's second laws. But why does the principle of least action also hold for classical fields like EM field and gravitational field? Is there any deep reason why it holds for both EM and gravitational field?