title: Dynamically creating routes from models in Laravel
body: <p>I have two models, <code>Group</code> and <code>Page</code>, where a group can have many pages. I'm trying to dynamically create routes based on these models, so that a /group-id/page-id kind of structure is automatically created.</p>
  
  <p>Here's what I've got so far:</p>
  
  <pre><code>foreach(App\Group::all() as $group)
  {
      Route::prefix($group-&gt;id)-&gt;group(function ()
      {
          foreach($group-&gt;pages as $page)
          {
              Route::get($page, function () {
                  return view($page-&gt;route_name);
              });
          }
      });
  }
  </code></pre>
  
  <p>The problem that's arising is because the routes are defined inside anonymous functions, the <code>$group</code> and <code>$page</code> variables aren't accessible to them. Passing through those variables to the function doesn't work either, as it's accepting a variable to come from a URL parameter.</p>