The match was Real Madrid's game in hand following their involvement in the 2017 Club World Cup, and the victory ensured that they would close the gap on second-placed Atletico Madrid to seven points.
That said, the gap from third-placed Los Blancos to league leaders Barcelona is still a huge 14 points.
Real Madrid boss Zinedine Zidane made five changes to the team that started Sunday's 5-3 win over Real Betis, with Kiko Casilla, Raphael Varane, Theo Hernandez, Isco and Karim Benzema all coming into the XI. Cristiano Ronaldo was left out altogether, while Toni Kroos, Marcelo and Luka Modric all missed out through injury.
Leganes took the lead in the sixth minute in spectacular fashion when centre-back Unai Bustinza threw his head at a goal-line clearance from Theo Hernandez, with the ball hitting the defender on the back before dropping over the line.
Real Madrid were level just five minutes later, however, when Lucas Vazquez found the bottom corner with a smart finish to register his seventh goal of the 2017-18 campaign.
The visitors had a super chance to go ahead in the 16th minute when Lucas freed Marco Asensio in a dangerous position, but the Spain international could only strike into the body of Cuellar.
Los Blancos did score their second in the 29th minute though, when a clever pass from Lucas freed Casemiro and the Brazilian found the bottom corner with a smart finish.
Leganes had more of the ball in the latter stages of the first period, but they went in behind as Real Madrid turned things around following a slow start in the Spanish capital.
Beauvue had a half-chance for Leganes just before the hour, but the striker saw his header blocked behind during a period where both teams were struggling to create chances.
Beauvue had an even better opportunity in the 65th minute when he met a low cross from El Zhar, only to be denied by a wonderful save from Casilla.
Gareth Bale came off the Real Madrid bench in the 76th minute, but the Welshman's introduction did little to raise the tempo as both teams continued to struggle in the final third of the field.
Bale came close to scoring a third for the away side in the latter stages, with the attacker bringing a smart save from Cuellar.
LEGANES (4-3-3): Cuellar; Tito, Siovas (Mantovani 46'), Bustinza, Rico; Gabriel, Gumbau (Perez 46'), Eraso; Ramos (Amrabat 72'), Beauvue, El Zhar
REAL MADRID (4-3-3): Casilla; Carvajal, Varane, Ramos, Theo; Casemiro, Kovacic (Ceballos 90'), Isco (Llorente 86'); Asensio, Benzema (Bale 76'), Lucas