博客开发之共享视图
为了避免多次查询相同的数据,可以在基础控制器中定义方法并使用View::share()分配模板变量,实现多次使用。
1.在Http\Controllers\Controller.php中定义多次使用的方法;
//前台共享视图
public function __construct()
{
$cates = Cate::orderBy('sort')->where('status','0')->get();
$web = System::first();
$topArticles = Article::orderBy('created_at','desc')->where(['is_top'=>'1','status'=>'0'])->limit(10)->get();
$viewData = [
'cates' => $cates,
'web' => $web,
'topArticles' => $topArticles,
];
View::share($viewData);
}
这里需要注意的是:在Laravel中0不能直接输出,需要使用单引号或者双引号包含,不然将默认为空!!
2.在HTML文件中引用即可,不需要在其余的控制器中再次查询
这样查询数据,极大地减少了代码量,避免多次查询相同的数据。