A magnetic field is like an invisible bubble around a planet. When charged particles from the Sun (solar wind) arrive, a strong magnetic field can deflect many of them, reducing how much they can erode the atmosphere over time.
Earth’s magnetic field is generated by moving molten metal in its core. That same field funnels particles toward the poles, creating auroras.
Some planets have surprisingly strong fields (Jupiter is a beast). Others, like Mars, have a much weaker global field today—which is one reason scientists are interested in how Mars lost much of its atmosphere.