To protect your soldiers from the attack, you can use any battle protection (2h, 8h, 24h, etc.).
Note that any soldiers outside the castle won't be protected.
If any attack happened on your soldiers outside the castle, you could return them to the castle immediately, whether they were collecting resources or anything else.