Dynamically creating routes from models in Laravel

Viewed 151

I have two models, Group and Page, 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.

Here's what I've got so far:

foreach(App\Group::all() as $group)
{
    Route::prefix($group->id)->group(function ()
    {
        foreach($group->pages as $page)
        {
            Route::get($page, function () {
                return view($page->route_name);
            });
        }
    });
}

The problem that's arising is because the routes are defined inside anonymous functions, the $group and $page 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.

1 Answers

Realized 10 seconds after posting that I could manage this in a much more laravel-y way

Route::get('/{group}/{page}', function (App\Group $group, App\Page $page)
{
    return view($page->route_name);
});
Related