【发布时间】:2021-02-25 03:51:04
【问题描述】:
我已经创建了一个主题系统,我正在尝试让主题的路由文件从数据库中提取页面并为其分配一个路由,下面是我的主题路由文件。我遇到的问题是来自我的ThemeSettings::all 模型请求的Undefined variable: theme。
Route.php(在主题中)
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use App\Models\ThemeSettings;
use App\Models\Pages;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('themes/main/index');
})->name('home');
$theme = ThemeSettings::all();
$pages = Pages::get();
foreach ($pages as $key => $page) {
Route::get('/' . $page->slug, function () {
return view($theme->location . $theme->name . '/' . $page->view);
})->name($page->slug);
}
Route::get('/terms', function () {
return 'Terms of use';
})->name('termsofuse');
Route::get('/privacy', function () {
return 'Privacy Policy';
})->name('privacypolicy');
Route::get('posts', 'PostController@index')->name('post.index');
Route::get('post/{slug}', 'PostController@details')->name('post.details');
Route::get('/category/{slug}', 'PostController@postByCategory')->name('category.posts');
Route::get('/tag/{slug}', 'PostController@postByTag')->name('tag.posts');
Route::get('/search', 'SearchController@search')->name('search');
Route::group(['middleware' => ['auth']], function () {
Route::post('favorite/{post}/add', 'FavoriteController@add')->name('post.favorite');
Route::post('comment/{post}', 'CommentController@store')->name('comment.store');
});
主题设置迁移
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateThemeSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('theme_settings', function (Blueprint $table) {
$table->id();
$table->string('name')->default('main');
$table->text('description');
$table->string('author');
$table->string('location')->default('resources/views/themes');
$table->string('view_location')->default('themes/');
$table->timestamps();
$table->boolean('is_theme')->default(false);
});
DB::table('theme_settings')->insert([
'description' => 'The core theme for Oracle CMS. A custom responsive framework with easy to use controls.',
'location' => 'resources/views/themes/',
'view_location' => 'themes/',
'author' => 'Spencer K Media'
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('theme_settings');
}
}
这些设置在网站的其他部分(包括管理区域)都有效,这就是我感到困惑的原因。
对此的任何帮助将不胜感激!提前谢谢!
【问题讨论】:
-
请删除不必要的路线代码
-
特别是,您不能在 php 中使用其范围之外的变量,除非在参数列表中或
use ($theme)中显式传递它。
标签: php laravel eloquent laravel-routing laravel-8