You need to keep high current supply/ground wiring away from the delicate stuff.
So the path from supply to electrmagnets, MOSFET drain, MOSFET source back to
the ground of the supply is the high current path.
Connect the logic stuff only to the MOSFET source and gate, at the MOSFET(s) so that
no high current path is shared with the sensitive logic side of things. This is a star ground
but the important point is the centre of the star is on the source lead of the MOSFET(s).
Another way to think about this is the MOSFET (or other switching device) has two
"ports", a control port with low current and drive by the logic is made from the
gate and source. The output port is the source and drain connections, carrying
the load current. These ports happen to intersect at a single node, the source pin,
but other than that keep them apart.
Avoid big loops, keep all the high current wiring as twisted pair where possible so that
outward and return current's cancel out from an interference perspective.
Since you have two supplies, 5V for the logic and 12V for your coils, its possible their
grounds are already connected via the mains earth, which would prevent a star ground
being possible - a ground loop is forced - this may lead to issues and if so the
optocoupler is the way to go if neither of the supplies can be made floating (safely).