I often say that pupils (male or female) can go to the toilet during my lesson but they'll have to give me five minutes (or more, equivalent to the lesson time they missed) at lunch to "catch up".
If they are genuinely in need of the loo, they agree to these terms (and I then subsequently 'forget' the catch-up time). The vast, vast majority suddenly decide their urgent need can in fact wait until the end of the lesson.
But this isn't a hard and fast rule. Like so many things in teaching, how you handle it is nuanced and responsive to the situation and the child. I have absolutely let a hard working and sensible girl go to the loo upon request without question because, well, I know her and I'm confident that she's only asking because she's in genuine need.
I've also let a sometimes disruptive and challenging girl go to the loo upon request without question, because, well, I know her too, and I can differentiate between her (frequent) attempts to skive and disrupt and a sincere and urgent need to go to the toilet.
Teachers don't always get things right. But we don't always get it wrong either. There is often a lot of skillful invisible managing and assessing of multiple simulaneous situations happening, that is dismissed when people who are not aware of the complexities say incredulously "For God's sake just let them go to the loo!"