php - 在 Laravel 5 中进行动态导航的正确方法

标签 php laravel-5

我正在使用 5.1 构建我的第一个 Laravel 应用程序,它是一个电子商务网站。

我从创建“静态”页面开始。我引用是因为页面不是从产品列表等动态生成的,但 html 仍然是从数据库中检索的。

我创建了一个 PagesController、一个 Page 模型、pages/index.blade.phppages/show .blade.php View ,以及一个 MasterTemplate.blade.php 模板文件。

我的 routes.php 看起来像:

$router->get('/', [
    'uses' => 'PagesController@index',
    'as' => 'pages.index'
]);

$router->get('/{page}', [
    'uses' => 'PagesController@show',
    'as' => 'pages.show'
]);

这很好用,我可以查看我的索引和数据库中的各个页面。

当我去添加我的导航时,我的问题出现了。由于我计划使用两种不同的导航栏(一种用于用户,一种用于管理员),我选择创建一个 _navDefault.php 文件以包含在 MasterTemplate 中。

去掉多余的 html 看起来像:

@foreach ($pages as $page)
    <li>{!! link_to_route('pages.show', $page->title, [$page->slug]) !!}</li>
@endforeach

这会很好地生成链接并且它们可以正常工作。但是因为我的 PagesController:

...
public function index()
{
    $pages = $this->page->get();
    return view('pages.index', compact('pages'));
}
...

$pages 仅存在于 index View 中,因此导航到 show View 会给我一个错误,即 $pages 是未定义的,这很合理。

我可以在 show 方法中定义 $pages,但我还会有其他 Controller ,例如 ProductControllerCartController 将在导航栏中有我需要的自己的页面,我不能很好地包含 $pages$products$每个 Controller 的每个 indexshow 方法中的 cart

我对 MVC 还是很陌生,所以我不确定处理这个问题的最佳方法,使用导航 Controller /模型或其他东西。

使用多个 Controller 实现动态导航栏的正确方法是什么?

最佳答案

这就是我能够在我的应用程序中随处使用动态导航栏的方式。

AppServiceProviderboot 方法中测试以下内容:

View::composer('*', function($view)
{
    $view->with('pages', Page::all());
});

* 表示所有 View 都将收到$pages

您现在可以将其提取到专用于查看 Composer 的服务提供商。

关于php - 在 Laravel 5 中进行动态导航的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32417795/

相关文章:

laravel - 传递给 Illuminate\\Database\\Query\\Builder::cleanBindings() 的参数 1 必须是数组类型,给定的字符串

php - 无法在 Controller 中获取用户 ID 并且 Auth::check() 不工作 - Laravel 5.8

php - 允许用户通过 Web GUI 构建自定义报告

php - 在 Laravel 5 中什么时候不应该使用 get()

jquery - laravel 5.2 使用ajax将表单数据发送到 Controller

php - 列出 MySQL DB 中的表并将表名称显示为下拉列表中的选项

php - Laravel 5.5 急切加载抛出错误 - 试图获取非对象的属性

PHP 生成一个完全白色的页面,没有错误、日志或标题。

php - 在 Yii 框架中创建 Controller

PhpMyAdmin 不工作 - XAMPP