带有类别(和子类别)的导航栏

时间:2018-11-09 18:56:24

标签: laravel

我需要你的帮助。我是新来的Laravel。 我想将所有类别和子类别放入导航栏,以便在每个页面上。我有一个类别模型。如何获得所有类别?我可以使用

之类的东西吗
Category::all()->get() etc.

在我的布局中,可以从布局中调用吗?

2 个答案:

答案 0 :(得分:0)

您应该使用视图编辑器将变量传递给所有页面。首先在App \ View \ Composer中创建一个视图编辑器;

    namespace App\View\Composers;
    use App\Category;
    use Illuminate\View\View;

    class InjectCategory
    {
       protected $categories;

       public function __construct(Category $categories)
       {
           $this->categories= $categories;
       }

       public function compose(View $view)
       {
           $categories= $this->categories->all();
           $view->with('categories',$categories);
       }
    }

然后,您应该将视图编辑器添加到AppServiceProvider的启动方法中。

public function boot(Request $request)
    {

        $this->app['view']->composer(['includes.frontend.menu'], Composers\InjectCategory::class);

    }

现在,您可以使用menu.blade.php中的$ categories值,并将其包含在要显示导航的任何页面的顶部。

答案 1 :(得分:0)

当我在Blog项目上工作时,我也遇到了同样的问题,我通过与所有视图共享数据来解决该问题,这是非常简单的方法。

在您的app/Provider/AppServiceProvider.php文件的boot方法中,添加以下代码:

 public function boot()
    {
        $categories = Category::all();
        view()->share('categories', $categories);    
    }

现在,您可以在每个视图中访问$categories,以获取更多详细信息,请访问此link

相关问题