The 21-year-old midfielder slotted in a cross from full-back Theo Hernandez to offer some respite to under fire coach Zinedine Zidane.
The last gasp success ended a run of three matches without victory.
Zidane has won eight trophies, including two Uefa Champions League titles, since taking over from Carlo Ancelotti in January 2016. Zidane led Madrid to the 2017 La Liga crown - their first domestic championship since 2012.
But the defence of that title has been disastrous. Bitter rivals Barcelona set the pace after 19 games with 51 points. While the Catalans are unbeaten in the league - having won 16 and drawn three matches, Madrid have lost four of their 18 La Liga fixtures and trail Barcelona by 19 points.
"The win over Leganes was a good result," said Zidane. "Perhaps it will be a turning point to allow us to go on a run of three or four good results.
"We have to use the win. We didn't play well but we got a positive result. and that's important. There are times when things don't go well but you've got to be patient and think about how you can be better."