Lattice energy
The amount of energy required to convert one mole of an ionic solid into gaseous ionic constituents
Or
The amount of energy released when one mole of ionic solid is formed from its gaseous ionic constituents.
Hydration energy
Hydration energy is the amount of energy released on the hydration of a one-mole ion. When the solvent is not water it is known as solvation energy.
Condition for a substance to become soluble
The solubility of a compound in water depends on the balance between lattice energy and hydration energy. When hydration energy of any ion overcomes the amount of lattice energy the bond dissociates, and solubility occurs.
Explanation
The atomic size of sodium and potassium is larger than that of magnesium and calcium and the charge on Ca and Mg is also high compared to Na and K. Thus, the lattice energies of carbonates and hydroxides formed by calcium and magnesium are much more than those of sodium and potassium.
Also, we know if the size of cation and anion decreases, solubility increases because hydration energy increases.
In the case of hydroxides and carbonates of sodium and potassium get dissociated into the water and get solubilized because their hydration energy is greater than that of lattice energy while the hydroxides and carbonates of magnesium and calcium are sparingly soluble in water because their hydration energy is less than that of lattice energy.