Php Laravel:将数据从数据库传递到路由

Php Laravel:将数据从数据库传递到路由,php,laravel,eloquent,laravel-routing,laravel-8,Php,Laravel,Eloquent,Laravel Routing,Laravel 8,我已经创建了一个主题系统,我试图让主题的路由文件从数据库中提取页面,并为其分配路由,下面是我的主题路由文件。我遇到的问题是来自我的ThemeSettings::allmodel请求的未定义变量:theme Route.php(主题中) $theme和$page不适用于闭包: Route::get('/' . $page->slug, function () { // $theme and $page are not defined here return view($the

我已经创建了一个主题系统,我试图让主题的路由文件从数据库中提取页面,并为其分配路由,下面是我的主题路由文件。我遇到的问题是来自我的
ThemeSettings::all
model请求的
未定义变量:theme

Route.php(主题中)


$theme
$page
不适用于闭包:

Route::get('/' . $page->slug, function () {
    // $theme and $page are not defined here
    return view($theme->location . $theme->name . '/' . $page->view);
})->name($page->slug);
因此,您可以通过
use()

但是,您还有另一个问题:

// $theme is a collection instance
$theme = ThemeSettings::all();
这意味着访问像
$theme->location
这样的属性也会导致异常

// You need to limit the result to a single instance.
$theme = ThemeSettings::where('something', 'some_value')->first();

请删除不必要的路线代码这是否回答了您的问题?特别是,如果不在参数列表中或使用
use($theme)
显式传递变量,就不能在php中使用其作用域之外的变量。
Route::get('/' . $page->slug, function () use ($theme, $page) {
    // All good now
    return view($theme->location . $theme->name . '/' . $page->view);
})->name($page->slug);
// $theme is a collection instance
$theme = ThemeSettings::all();
// You need to limit the result to a single instance.
$theme = ThemeSettings::where('something', 'some_value')->first();