我正在建立一个网站,菜单可由管理员管理,我的问题是如何安装选择显示在所有页面上的东西。
起初,我正在查询控制器所有动作中的菜单,但是我想对其进行优化,只是不知道如何做。
我的控制器。
<?php
namespace App\Http\Controllers;
use App\Categorias;
use Illuminate\Http\Request;
class FrontendController extends Controller {
public $template = 'default';
// Retorna Navegação
public function retornaNavegacao(){
$sql = Categorias::where([
['exibir', '=', 1], ['publicado', '=', 1]
])
->get();
return $sql;
}
// Página 'Categorias'
public function categoria(){
return view('frontend.'.$this->template.'.categorias.index',
array(
'mainMenu' => $this->retornaNavegacao(),
)
);
}
// Página 'Produtos'
public function produto(){
return view('frontend.'.$this->template.'.produtos.index',
array(
'mainMenu' => $this->retornaNavegacao(),
)
);
}
// Página 'Contato'
public function contato(){
return view('frontend.'.$this->template.'.contato.index',
array(
'mainMenu' => $this->retornaNavegacao(),
)
);
}
}
函数retornaNavegacao()仅查询数据库并返回所有已注册的菜单(搜索所有子类别都有关系)。
但是我必须在控制器的所有动作中重复菜单代码,但我认为它可能有一种更聪明的方式,不必在所有动作中重复此代码。
答案 0 :(得分:1)
在AppServiceProvider
类中编辑boot
方法
public function boot()
{
$categories = Categorias::where([
['exibir', '=', 1],
['publicado', '=', 1]
])
->get();
View::composer('*', function ($view) {
$view->with(['mainMenu' => 'categories']);
});
}
您还可以使用laravel的所有功能
public function boot()
{
$mainMenu = Categorias::whereWxibir(1)
->wherePublicado(1)
->get();
View::composer('*', function ($view) {
$view->with(compact('mainMenu'));
});
}
答案 1 :(得分:0)
您可以通过应用服务提供商的启动方法在所有视图中共享一个变量。
public function boot()
{
$mainMenu = $this->retornaNavegacao(),
view()->share(compact('mainMenu'));
}
如果您只想在某些特定视图中共享变量,则可以制作自己的view composer。