Please and thank you for any suggestions
The quest to understand how oral narratives formed, diffused, and changed over time was at the heart of the earliest efforts of scholarly folklorists, who in the early nineteenth century began to contemplate the question you pose here. By "oral narrative" I am including folktales and legends (and by default myths - for definitions, see below).
The first formal attempt at a methodology to answer your question was developed in Finland by Julius Krohn (1835-1888) and his son Kaarle Krohn (1863-1933). That method became known as the Finnish Historic-Geographic Method because it considered the geographic spread of a narrative combined with past manifestations to attempt to find the "ur" form of the story - the first telling, and then to understand how that story diffused and changed over time and place.
Many folklorists turn away from the Finnish method because the "ur" form is too often illusive and real answers about the past of oral narratives - the heart of your question - can be extremely difficult to understand. Many other folklorists - myself included - still find value in the Finnish method, but as for myself, I approach the method and its question - your question! - with a meandering sideways gate. In the 1920s, my mentor, Sven S. Liljeblad (1899-2000) and his mentor, the great theoretician, Carl Wilhelm von Sydow (1878-1952) adapted the Finnish method with what became known as the Swedish or Ecotype approach to answer your question, and I have adapted that approach for much of my work. For an essay on Liljeblad and von Sydow, see my brief work, Nazis, Trolls and the Grateful Dead. My recent The Folklore of Cornwall (2018) uses that approach.
To attempt to answer your question from a historical perspective, Alan Dundes assembled his fine book, a collection of essays from many early folklorists: International Folkloristics: Classic Contributions by the Founders of Folklore (1999). Some of the essays may be difficult reading, but Dundes was a gifted writer and a brilliant folklorist, and his introductions to each essay are excellent. It is worth reading even if one skips from introduction to introduction!
One of the things one frequently encounters when it comes to the origin of legends is a bit of modern folk belief that one often encounters on this sub: that is, that "every legend is based on something real in the past." This element of modern folklore does not always hold water, and we must all be watchful of those who declare they have found the "true origin of a legend." Too often these declarations are based on speculation that cannot be proven and must be taken on faith - only to be discarded until the next person presents the next "brilliant" Eureka moment that they have found the "true origin of the same legend" - again based on speculation. Speculation is not proof or truth!
[continued with a note about terms]...