Preheat the oven to 375 degrees and lightly grease a medium baking dish.
Melt the butter in a saucepan over medium heat. Add the onion and garlic. Cook until the onion softens.
Stir in the flour and cook for one minute. Slowly whisk in the milk. Add the salt and pepper. Continue stirring until the sauce thickens.
Spread half the potato slices in the baking dish. Scatter half the diced ham over the potatoes. Pour half the sauce on top and sprinkle with half the cheese.
Repeat the layers with the remaining potatoes, ham, sauce, and cheese.
Cover the dish with foil and bake for 40 minutes. Remove the foil and bake for another 20 minutes until the top turns golden and the potatoes are tender when pierced with a knife.