Preheat oven to 375°F (190°C).
Melt butter in a saucepan over medium heat. Add flour. Whisk for 1 minute.
Slowly add milk, whisking until thick and smooth. Season with salt and pepper.
Stir in cheese until melted and creamy. Remove from heat.
Layer half of the sliced potatoes in a greased baking dish. Add half the onion and garlic if using.
Pour half the cheese sauce over the layer.
Repeat with remaining potatoes, onions, and sauce.
Cover with foil and bake for 40 minutes.
Uncover and bake another 15–20 minutes, until golden and bubbly.
Let rest for 10 minutes before serving. Garnish with parsley if desired.