模型:Comment.php
class Comment extends Eloquent {
protected $table = 'comments';
public $timestamps = true;
}
控制器:PageController.php
class PageController extends BaseController {
$top_comments = Comment::take(3)->get();
return View::make('page', array('top_comments' => $top_comments));
}
视图:pageblade.php
@foreach ($top_comments as $comment)
user #{{ $comment->user_id }}:<br />
{{ $comment->comment}}
@endforeach
这与page.blade.php
视图非常配合,我可以将其定义为路由(/page
(。然而,我似乎不知道如何在全球范围内实现这一目标。
示例:我希望能够在master.blade.php
文件中使用包含$top_comments
的@foreach
。现在,如果我使用上面的,它在/page
上效果很好,但在/
、/about
、/tos
上效果不佳
您可以使用View::share('top_comments', Comment::take(3)->get());
使其在任何地方都可用。当然,如果你想在所有可能的视图中看到它,无论你加载什么页面,你都必须把它放在加载的地方。(其中一个地方是你的BaseController
的__construct()
方法,但我怀疑这是否是最佳实践。我不确定我自己会把它放在哪里。(
另一种方法是利用视图编辑器,比如:
View::composer('master', function($view)
{
$view->with('top_comments', Comment::take(3)->get());
});
如果您的意思是无论从哪里加载它,都希望它出现在master.blade.php
中,这是有效的,因为它绑定到该视图。如果您选择此选项,我建议您创建一个文件composers.php
并将其包含在app/start/global.php
中。
也就是说,我假设上面的控制器示例遗漏了一些内容,因为它看起来缺少一个方法声明。